Datasets:
Incremental country-laws-ir GraphRAG release for justicedao/ipfs_belarus_laws_ir
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +1 -59
- README.md +131 -2
- build.py +444 -0
- country_laws_ir/__init__.py +1 -1
- country_laws_ir/__main__.py +123 -11
- country_laws_ir/auth.py +26 -4
- country_laws_ir/build.py +307 -100
- country_laws_ir/catalog.py +82 -9
- country_laws_ir/cidutil.py +21 -0
- country_laws_ir/coverage.py +452 -0
- country_laws_ir/duckdb_store.py +408 -0
- country_laws_ir/incremental.py +500 -0
- country_laws_ir/normalize.py +48 -11
- country_laws_ir/package.py +149 -79
- country_laws_ir/query.py +17 -1
- country_laws_ir/raw_package.py +324 -0
- country_laws_ir/sparse.py +114 -0
- country_laws_ir/spill.py +80 -311
- country_laws_ir/upload.py +122 -14
- country_laws_ir/vectors.py +108 -18
- data/bm25/documents/part-000000.parquet +2 -2
- data/bm25/documents/part-000001.parquet +2 -2
- data/bm25/postings/part-000000.parquet +2 -2
- data/corpus/part-000000.parquet +2 -2
- data/corpus/part-000001.parquet +2 -2
- data/graph/adjacency/in/part-000000.parquet +3 -0
- data/graph/adjacency/in/part-000001.parquet +3 -0
- data/graph/adjacency/in/part-000002.parquet +3 -0
- data/graph/adjacency/in/part-000003.parquet +3 -0
- data/graph/adjacency/in/part-000004.parquet +3 -0
- data/graph/adjacency/in/part-000005.parquet +3 -0
- data/graph/adjacency/in/part-000006.parquet +3 -0
- data/graph/adjacency/out/part-000000.parquet +3 -0
- data/graph/adjacency/out/part-000001.parquet +3 -0
- data/graph/adjacency/out/part-000002.parquet +3 -0
- data/graph/adjacency/out/part-000003.parquet +3 -0
- data/graph/adjacency/out/part-000004.parquet +3 -0
- data/graph/adjacency/out/part-000005.parquet +3 -0
- data/graph/adjacency/out/part-000006.parquet +3 -0
- data/graph/edges/part-000000.parquet +2 -2
- data/graph/edges/part-000001.parquet +2 -2
- data/graph/edges/part-000002.parquet +2 -2
- data/graph/edges/part-000003.parquet +2 -2
- data/graph/edges/part-000004.parquet +2 -2
- data/graph/edges/part-000005.parquet +2 -2
- data/graph/edges/part-000006.parquet +2 -2
- data/graph/edges/part-000007.parquet +2 -2
- data/graph/edges/part-000008.parquet +2 -2
- data/graph/edges/part-000009.parquet +2 -2
- data/graph/edges/part-000010.parquet +2 -2
.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
CHANGED
|
@@ -1,3 +1,132 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
-
Belarus
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
- belarus
|
| 13 |
+
pretty_name: Belarus 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 |
+
# Belarus legislation IR (CID-keyed sparse GraphRAG)
|
| 58 |
+
|
| 59 |
+
Research retrieval release of `endomorphosis/ipfs_belarus_laws` (revision `b5fe172bd073c7217d379965fb38646fc2c60bc3`) 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 Belarus 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_belarus_laws_ir`.
|
| 70 |
+
|
| 71 |
+
## Counts
|
| 72 |
+
|
| 73 |
+
| Field | Value |
|
| 74 |
+
| --- | --- |
|
| 75 |
+
| Laws (corpus units) | 0 |
|
| 76 |
+
| Articles (corpus units) | 7206 |
|
| 77 |
+
| Canonical docs | 7206 |
|
| 78 |
+
| BM25 terms | 3186 |
|
| 79 |
+
| BM25 postings | 38886 |
|
| 80 |
+
| Graph nodes | 7276 |
|
| 81 |
+
| Graph edges | 50442 |
|
| 82 |
+
| Vectors | 7206 × 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_belarus_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_belarus_laws`. CIDs identify local content; they do not prove public IPFS pinning.
|
build.py
ADDED
|
@@ -0,0 +1,444 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""End-to-end build: normalize → incremental vectors → BM25 → graph → package.
|
| 2 |
+
|
| 3 |
+
Default mode is ``auto``: skip when the endomorphosis source revision is
|
| 4 |
+
unchanged, otherwise delta-refresh embeddings by ``entry_cid`` and rebuild
|
| 5 |
+
BM25/graph from the current corpus. Publication to ``justicedao/*`` is opt-in
|
| 6 |
+
via ``upload=True``.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
|
| 13 |
+
import json
|
| 14 |
+
|
| 15 |
+
import pandas as pd
|
| 16 |
+
import traceback
|
| 17 |
+
from datetime import datetime, timezone
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from typing import Any
|
| 20 |
+
|
| 21 |
+
from .sparse import export_sparse_graphrag
|
| 22 |
+
from .mem import MemAbort, checkpoint, log_mem
|
| 23 |
+
from .spill import spill_dir_for, spill_pickle
|
| 24 |
+
from .package import package_from_spill, package_release
|
| 25 |
+
from .catalog import get_country, indexable_countries, target_repo
|
| 26 |
+
|
| 27 |
+
from .incremental import (
|
| 28 |
+
fetch_hub_prior,
|
| 29 |
+
load_embedding_cache,
|
| 30 |
+
load_prior_release,
|
| 31 |
+
load_release_vectors_by_cid,
|
| 32 |
+
merge_embedding_maps,
|
| 33 |
+
plan_rebuild,
|
| 34 |
+
save_embedding_cache,
|
| 35 |
+
)
|
| 36 |
+
from .normalize import build_corpus, load_source
|
| 37 |
+
from .auth import configure_hf
|
| 38 |
+
from .vectors import (
|
| 39 |
+
DIMENSION,
|
| 40 |
+
MODEL_NAME,
|
| 41 |
+
assemble_embeddings,
|
| 42 |
+
embeddings_available,
|
| 43 |
+
embeddings_by_cid,
|
| 44 |
+
layout_stub_vectors,
|
| 45 |
+
layout_vectors,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
ROOT = Path(os.environ.get("COUNTRY_LAWS_IR_ROOT", str(Path.home() / ".ipfs_datasets" / "country-laws-ir")))
|
| 49 |
+
CACHE = ROOT / "cache"
|
| 50 |
+
RELEASES = ROOT / "releases"
|
| 51 |
+
REPORTS = ROOT / "reports"
|
| 52 |
+
PROGRESS = ROOT / "progress.jsonl"
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _log(msg: str) -> None:
|
| 56 |
+
ts = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
| 57 |
+
print(f"[{ts}] {msg}", flush=True)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def record_progress(event: dict[str, Any]) -> None:
|
| 61 |
+
event = dict(event)
|
| 62 |
+
event.setdefault("ts", datetime.now(timezone.utc).isoformat())
|
| 63 |
+
with PROGRESS.open("a", encoding="utf-8") as f:
|
| 64 |
+
f.write(json.dumps(event, ensure_ascii=False) + "\n")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _prior_dir_for(
|
| 68 |
+
slug: str,
|
| 69 |
+
out: Path,
|
| 70 |
+
prior_dir: Path | None,
|
| 71 |
+
*,
|
| 72 |
+
fetch_hub: bool = True,
|
| 73 |
+
) -> Path | None:
|
| 74 |
+
if prior_dir is not None:
|
| 75 |
+
return Path(prior_dir)
|
| 76 |
+
if out.is_dir() and (out / "manifest.json").is_file():
|
| 77 |
+
return out
|
| 78 |
+
default = RELEASES / f"ipfs_{slug}_laws_ir"
|
| 79 |
+
if default.is_dir() and (default / "manifest.json").is_file() and default.resolve() != out.resolve():
|
| 80 |
+
return default
|
| 81 |
+
if not fetch_hub:
|
| 82 |
+
return None
|
| 83 |
+
hub = fetch_hub_prior(slug, cache_root=CACHE / "hub-ir")
|
| 84 |
+
if hub is not None:
|
| 85 |
+
_log(f"using justicedao prior {hub}")
|
| 86 |
+
return hub
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _encode_vectors(
|
| 90 |
+
*,
|
| 91 |
+
corpus: pd.DataFrame,
|
| 92 |
+
country_slug: str,
|
| 93 |
+
prior,
|
| 94 |
+
plan,
|
| 95 |
+
skip_vectors: bool,
|
| 96 |
+
device: str,
|
| 97 |
+
) -> tuple[dict[str, Any], str | None, dict[str, Any]]:
|
| 98 |
+
import gc
|
| 99 |
+
|
| 100 |
+
vector_report: dict[str, Any] = {"status": "stub"}
|
| 101 |
+
vector_blocker = None
|
| 102 |
+
if skip_vectors:
|
| 103 |
+
vectors = layout_stub_vectors(corpus, reason="skip_vectors flag")
|
| 104 |
+
return vectors, "skip_vectors", {"status": "stub", "reason": "skip_vectors"}
|
| 105 |
+
|
| 106 |
+
cid_cache_path = CACHE / "embeddings" / f"{country_slug}_by_cid.parquet"
|
| 107 |
+
prior_by_cid = {}
|
| 108 |
+
if plan.reuse_embeddings:
|
| 109 |
+
prior_by_cid = merge_embedding_maps(
|
| 110 |
+
load_embedding_cache(cid_cache_path),
|
| 111 |
+
None if prior is None else load_release_vectors_by_cid(prior.directory),
|
| 112 |
+
)
|
| 113 |
+
_log(f"embedding cache reused_cids={len(prior_by_cid)}")
|
| 114 |
+
try:
|
| 115 |
+
positional = CACHE / "embeddings" / f"{country_slug}.npy"
|
| 116 |
+
embeddings, vector_report = assemble_embeddings(
|
| 117 |
+
corpus,
|
| 118 |
+
prior_by_cid,
|
| 119 |
+
encode_missing=embeddings_available(),
|
| 120 |
+
device=device,
|
| 121 |
+
checkpoint_path=str(positional),
|
| 122 |
+
)
|
| 123 |
+
if (
|
| 124 |
+
vector_report.get("status") in {"stub_missing_encoder", "incomplete"}
|
| 125 |
+
and not int(vector_report.get("n_reused") or 0)
|
| 126 |
+
):
|
| 127 |
+
vector_blocker = vector_report.get("reason") or vector_report.get("status")
|
| 128 |
+
vectors = layout_stub_vectors(corpus, reason=str(vector_blocker))
|
| 129 |
+
return vectors, vector_blocker, vector_report
|
| 130 |
+
vectors = layout_vectors(corpus, embeddings)
|
| 131 |
+
if int(vector_report.get("n_reused") or 0) and vector_report.get("status") != "reused":
|
| 132 |
+
vectors["stats"]["status"] = "partial"
|
| 133 |
+
vectors["stats"]["n_reused"] = int(vector_report.get("n_reused") or 0)
|
| 134 |
+
vectors["stats"]["n_missing"] = int(vector_report.get("n_missing") or 0)
|
| 135 |
+
vector_blocker = vector_report.get("reason") or vector_report.get("status")
|
| 136 |
+
save_embedding_cache(
|
| 137 |
+
cid_cache_path,
|
| 138 |
+
merge_embedding_maps(prior_by_cid, embeddings_by_cid(corpus, embeddings)),
|
| 139 |
+
model_name=MODEL_NAME,
|
| 140 |
+
dimension=DIMENSION,
|
| 141 |
+
)
|
| 142 |
+
del embeddings
|
| 143 |
+
gc.collect()
|
| 144 |
+
_log(
|
| 145 |
+
f"vectors n={vectors['stats']['n_vectors']} shards={vectors['stats']['shard_count']} "
|
| 146 |
+
f"reused={vector_report.get('n_reused')} encoded={vector_report.get('n_encoded')}"
|
| 147 |
+
)
|
| 148 |
+
return vectors, None, vector_report
|
| 149 |
+
except Exception as exc:
|
| 150 |
+
vector_blocker = f"embedding_failed: {exc}"
|
| 151 |
+
_log(f"vector embedding failed; writing stub ({exc})")
|
| 152 |
+
vectors = layout_stub_vectors(corpus, reason=vector_blocker)
|
| 153 |
+
return vectors, vector_blocker, {"status": "failed", "reason": str(exc)}
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def build_country(
|
| 157 |
+
source: str,
|
| 158 |
+
out: Path | None = None,
|
| 159 |
+
upload: bool = False,
|
| 160 |
+
device: str = "cpu",
|
| 161 |
+
neighbor_k: int = 8,
|
| 162 |
+
skip_vectors: bool = False,
|
| 163 |
+
mode: str = "auto",
|
| 164 |
+
force: bool = False,
|
| 165 |
+
prior_dir: Path | None = None,
|
| 166 |
+
fetch_hub_prior_ir: bool = True,
|
| 167 |
+
) -> dict[str, Any]:
|
| 168 |
+
country = get_country(source)
|
| 169 |
+
if not country.get("indexable", True):
|
| 170 |
+
raise RuntimeError(f"{country['repo']} is excluded: {country.get('skip_reason')}")
|
| 171 |
+
repo = country["repo"]
|
| 172 |
+
out = Path(out) if out else RELEASES / f"ipfs_{country['slug']}_laws_ir"
|
| 173 |
+
local_dir = country.get("local_source_dir") or (
|
| 174 |
+
str(Path(source).resolve())
|
| 175 |
+
if Path(source).is_dir()
|
| 176 |
+
and (
|
| 177 |
+
(Path(source) / "data" / "laws.parquet").is_file()
|
| 178 |
+
or (Path(source) / "laws.parquet").is_file()
|
| 179 |
+
)
|
| 180 |
+
else None
|
| 181 |
+
)
|
| 182 |
+
_log(
|
| 183 |
+
f"build start {repo} -> {out} (upload={upload} mode={mode} force={force}) local={local_dir}"
|
| 184 |
+
)
|
| 185 |
+
configure_hf()
|
| 186 |
+
CACHE.mkdir(parents=True, exist_ok=True)
|
| 187 |
+
REPORTS.mkdir(parents=True, exist_ok=True)
|
| 188 |
+
laws, articles, source_meta = load_source(local_dir or repo, CACHE)
|
| 189 |
+
_log(
|
| 190 |
+
f"source loaded laws={source_meta['n_laws_source']} "
|
| 191 |
+
f"articles={source_meta['n_articles_source']} rev={source_meta['source_revision']}"
|
| 192 |
+
)
|
| 193 |
+
prior = load_prior_release(
|
| 194 |
+
_prior_dir_for(
|
| 195 |
+
country["slug"],
|
| 196 |
+
out,
|
| 197 |
+
prior_dir,
|
| 198 |
+
fetch_hub=fetch_hub_prior_ir,
|
| 199 |
+
)
|
| 200 |
+
)
|
| 201 |
+
plan = plan_rebuild(
|
| 202 |
+
mode=mode, source_meta=source_meta, prior=prior, force=force
|
| 203 |
+
)
|
| 204 |
+
if plan.skip_build:
|
| 205 |
+
_log(f"skip unchanged {country['slug']} rev={plan.source_revision}")
|
| 206 |
+
result = {
|
| 207 |
+
"country": country["slug"],
|
| 208 |
+
"source": repo,
|
| 209 |
+
"source_revision": source_meta["source_revision"],
|
| 210 |
+
"out": str(out),
|
| 211 |
+
"target_hub_id": target_repo(country["slug"]),
|
| 212 |
+
"skipped": True,
|
| 213 |
+
"incremental": plan.to_dict(),
|
| 214 |
+
"normalization": {"n_out": plan.delta.current_count if plan.delta else 0},
|
| 215 |
+
"vector_blocker": None,
|
| 216 |
+
"neighbor_via": None,
|
| 217 |
+
"schema_version": "country-laws-ir-graphrag/v1",
|
| 218 |
+
}
|
| 219 |
+
record_progress({"event": "skipped_unchanged", **{k: v for k, v in result.items() if k != "normalization"}})
|
| 220 |
+
return result
|
| 221 |
+
|
| 222 |
+
corpus, norm_report = build_corpus(laws, articles, source_meta)
|
| 223 |
+
report_path = REPORTS / f"{country['slug']}_normalization.json"
|
| 224 |
+
report_path.write_text(json.dumps(norm_report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
| 225 |
+
(REPORTS / "normalization.json").write_text(
|
| 226 |
+
json.dumps(norm_report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
|
| 227 |
+
)
|
| 228 |
+
_log(
|
| 229 |
+
f"normalized docs={len(corpus)} unit={norm_report['unit']} "
|
| 230 |
+
f"dropped={norm_report['n_dropped_total']} report={report_path}"
|
| 231 |
+
)
|
| 232 |
+
if corpus.empty:
|
| 233 |
+
raise RuntimeError("Normalized corpus is empty; refusing to package")
|
| 234 |
+
|
| 235 |
+
import gc
|
| 236 |
+
|
| 237 |
+
plan = plan_rebuild(
|
| 238 |
+
mode=mode,
|
| 239 |
+
source_meta=source_meta,
|
| 240 |
+
prior=prior,
|
| 241 |
+
current_corpus=corpus,
|
| 242 |
+
force=force,
|
| 243 |
+
)
|
| 244 |
+
_log(
|
| 245 |
+
f"rebuild kind={plan.kind.value} reuse_embeddings={plan.reuse_embeddings} "
|
| 246 |
+
f"added={0 if plan.delta is None else plan.delta.n_added} "
|
| 247 |
+
f"removed={0 if plan.delta is None else plan.delta.n_removed}"
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
n_docs = len(corpus)
|
| 251 |
+
spill = spill_dir_for(country["slug"], CACHE)
|
| 252 |
+
spill.mkdir(parents=True, exist_ok=True)
|
| 253 |
+
corpus_ckpt = CACHE / f"{country['slug']}_corpus.parquet"
|
| 254 |
+
corpus.to_parquet(corpus_ckpt, index=False)
|
| 255 |
+
checkpoint("after_normalize", log=_log)
|
| 256 |
+
|
| 257 |
+
vectors, vector_blocker, vector_report = _encode_vectors(
|
| 258 |
+
corpus=corpus,
|
| 259 |
+
country_slug=country["slug"],
|
| 260 |
+
prior=prior,
|
| 261 |
+
plan=plan,
|
| 262 |
+
skip_vectors=skip_vectors,
|
| 263 |
+
device=device,
|
| 264 |
+
)
|
| 265 |
+
spill_pickle(spill / "vectors.pkl", vectors)
|
| 266 |
+
del vectors
|
| 267 |
+
gc.collect()
|
| 268 |
+
checkpoint("vectors_spilled", log=_log)
|
| 269 |
+
extra_manifest = {"incremental": {**plan.to_dict(), "vectors": vector_report}}
|
| 270 |
+
|
| 271 |
+
neighbor_via = "hf_graphrag"
|
| 272 |
+
if out.exists():
|
| 273 |
+
import shutil as _shutil
|
| 274 |
+
|
| 275 |
+
_shutil.rmtree(out)
|
| 276 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 277 |
+
_log(f"sparse GraphRAG via hf_graphrag.bm25/graph parquet builders n={n_docs}")
|
| 278 |
+
sparse_report = export_sparse_graphrag(corpus, out)
|
| 279 |
+
extra_manifest["sparse"] = sparse_report
|
| 280 |
+
with open(spill / "vectors.pkl", "rb") as _vf:
|
| 281 |
+
import pickle as _pickle
|
| 282 |
+
|
| 283 |
+
vectors = _pickle.load(_vf)
|
| 284 |
+
dummy_bm25 = {
|
| 285 |
+
"documents": pd.DataFrame(),
|
| 286 |
+
"postings": pd.DataFrame(),
|
| 287 |
+
"stats": (sparse_report.get("bm25") or {}).get("bm25")
|
| 288 |
+
or (sparse_report.get("bm25") or {}),
|
| 289 |
+
}
|
| 290 |
+
dummy_graph = {
|
| 291 |
+
"nodes": pd.DataFrame(),
|
| 292 |
+
"edges": pd.DataFrame(),
|
| 293 |
+
"incoming": pd.DataFrame(),
|
| 294 |
+
"outgoing": pd.DataFrame(),
|
| 295 |
+
"stats": sparse_report.get("graph") or {},
|
| 296 |
+
}
|
| 297 |
+
code_root = Path(__file__).resolve().parent.parent
|
| 298 |
+
manifest = package_release(
|
| 299 |
+
out,
|
| 300 |
+
corpus,
|
| 301 |
+
dummy_bm25,
|
| 302 |
+
dummy_graph,
|
| 303 |
+
vectors,
|
| 304 |
+
source_meta,
|
| 305 |
+
country,
|
| 306 |
+
code_root,
|
| 307 |
+
normalization_report=norm_report,
|
| 308 |
+
extra_manifest=extra_manifest,
|
| 309 |
+
wipe=False,
|
| 310 |
+
skip_bm25_graph=True,
|
| 311 |
+
)
|
| 312 |
+
del corpus, vectors
|
| 313 |
+
gc.collect()
|
| 314 |
+
_log(f"packaged {out}")
|
| 315 |
+
result = {
|
| 316 |
+
"country": country["slug"],
|
| 317 |
+
"source": repo,
|
| 318 |
+
"source_revision": source_meta["source_revision"],
|
| 319 |
+
"out": str(out),
|
| 320 |
+
"target_hub_id": target_repo(country["slug"]),
|
| 321 |
+
"counts": manifest["counts"],
|
| 322 |
+
"normalization": norm_report,
|
| 323 |
+
"vector_blocker": vector_blocker,
|
| 324 |
+
"neighbor_via": neighbor_via,
|
| 325 |
+
"schema_version": manifest["schema_version"],
|
| 326 |
+
"skipped": False,
|
| 327 |
+
"incremental": extra_manifest["incremental"],
|
| 328 |
+
}
|
| 329 |
+
if upload:
|
| 330 |
+
from .upload import upload_release
|
| 331 |
+
|
| 332 |
+
hub = upload_release(out, target_repo(country["slug"]))
|
| 333 |
+
result["hub"] = hub
|
| 334 |
+
_log(f"uploaded {hub['url']} rev={hub['revision']}")
|
| 335 |
+
record_progress({"event": "uploaded", **result})
|
| 336 |
+
else:
|
| 337 |
+
record_progress({"event": "built_local", **{k: v for k, v in result.items() if k != "normalization"}})
|
| 338 |
+
return result
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def batch(
|
| 342 |
+
slugs: list[str] | None = None,
|
| 343 |
+
upload: bool = False,
|
| 344 |
+
skip_done: bool = True,
|
| 345 |
+
mode: str = "auto",
|
| 346 |
+
force: bool = False,
|
| 347 |
+
skip_vectors: bool = False,
|
| 348 |
+
) -> list[dict[str, Any]]:
|
| 349 |
+
"""Build every indexable country. Unchanged Hub revisions are skipped in auto mode.
|
| 350 |
+
|
| 351 |
+
``skip_done`` is kept for compatibility: it no longer skips a country whose
|
| 352 |
+
source revision changed. Pass ``force=True`` (or ``--no-skip-done``) to
|
| 353 |
+
rebuild regardless of CID overlap.
|
| 354 |
+
"""
|
| 355 |
+
targets = slugs or [c["slug"] for c in indexable_countries()]
|
| 356 |
+
if "malta" in targets:
|
| 357 |
+
targets = ["malta"] + [s for s in targets if s != "malta"]
|
| 358 |
+
results = []
|
| 359 |
+
rebuild_force = force or not skip_done
|
| 360 |
+
for slug in targets:
|
| 361 |
+
try:
|
| 362 |
+
results.append(
|
| 363 |
+
build_country(
|
| 364 |
+
slug,
|
| 365 |
+
upload=upload,
|
| 366 |
+
mode=mode,
|
| 367 |
+
force=rebuild_force,
|
| 368 |
+
skip_vectors=skip_vectors,
|
| 369 |
+
)
|
| 370 |
+
)
|
| 371 |
+
except Exception as exc:
|
| 372 |
+
_log(f"FAILED {slug}: {exc}")
|
| 373 |
+
record_progress(
|
| 374 |
+
{
|
| 375 |
+
"event": "failed",
|
| 376 |
+
"country": slug,
|
| 377 |
+
"error": str(exc),
|
| 378 |
+
"traceback": traceback.format_exc(),
|
| 379 |
+
}
|
| 380 |
+
)
|
| 381 |
+
continue
|
| 382 |
+
return results
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def reindex_from_gaps(
|
| 386 |
+
*,
|
| 387 |
+
upload: bool = False,
|
| 388 |
+
slugs: list[str] | None = None,
|
| 389 |
+
limit: int | None = None,
|
| 390 |
+
max_corpus_rows: int | None = 20_000,
|
| 391 |
+
skip_vectors: bool = False,
|
| 392 |
+
workers: int = 4,
|
| 393 |
+
mode: str = "auto",
|
| 394 |
+
) -> list[dict[str, Any]]:
|
| 395 |
+
"""Scan Hub gaps and incrementally rebuild stale/missing country IR.
|
| 396 |
+
|
| 397 |
+
Default cap skips huge corpora (Finland, Dominican Republic). Pass
|
| 398 |
+
``max_corpus_rows=None`` to include them.
|
| 399 |
+
"""
|
| 400 |
+
from .coverage import gap_report
|
| 401 |
+
|
| 402 |
+
if slugs is None:
|
| 403 |
+
report = gap_report(workers=workers)
|
| 404 |
+
rows = [c for c in report["countries"] if c.get("rebuild")]
|
| 405 |
+
rows.sort(key=lambda r: int(r.get("corpus_rows") or 0))
|
| 406 |
+
if max_corpus_rows is not None:
|
| 407 |
+
rows = [
|
| 408 |
+
r
|
| 409 |
+
for r in rows
|
| 410 |
+
if int(r.get("corpus_rows") or 0) <= int(max_corpus_rows)
|
| 411 |
+
]
|
| 412 |
+
if limit is not None:
|
| 413 |
+
rows = rows[: int(limit)]
|
| 414 |
+
slugs = [str(r["slug"]) for r in rows]
|
| 415 |
+
_log(
|
| 416 |
+
f"reindex targets n={len(slugs)} "
|
| 417 |
+
f"(from scan rebuild={len(report.get('rebuild') or [])})"
|
| 418 |
+
)
|
| 419 |
+
results: list[dict[str, Any]] = []
|
| 420 |
+
for slug in slugs:
|
| 421 |
+
_log(f"reindex start {slug}")
|
| 422 |
+
try:
|
| 423 |
+
results.append(
|
| 424 |
+
build_country(
|
| 425 |
+
slug,
|
| 426 |
+
upload=upload,
|
| 427 |
+
mode=mode,
|
| 428 |
+
skip_vectors=skip_vectors,
|
| 429 |
+
fetch_hub_prior_ir=True,
|
| 430 |
+
)
|
| 431 |
+
)
|
| 432 |
+
except Exception as exc:
|
| 433 |
+
_log(f"FAILED {slug}: {exc}")
|
| 434 |
+
record_progress(
|
| 435 |
+
{
|
| 436 |
+
"event": "failed",
|
| 437 |
+
"country": slug,
|
| 438 |
+
"error": str(exc),
|
| 439 |
+
"traceback": traceback.format_exc(),
|
| 440 |
+
}
|
| 441 |
+
)
|
| 442 |
+
results.append({"country": slug, "skipped": False, "error": str(exc)})
|
| 443 |
+
continue
|
| 444 |
+
return results
|
country_laws_ir/__init__.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
"""Country-law CID-keyed sparse GraphRAG packager (SkillCenter / publicus-ir family)."""
|
| 2 |
|
| 3 |
-
__version__ = "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"
|
|
|
|
| 1 |
"""Country-law CID-keyed sparse GraphRAG packager (SkillCenter / publicus-ir family)."""
|
| 2 |
|
| 3 |
+
__version__ = "0.5.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"
|
country_laws_ir/__main__.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
"""python -m country_laws_ir {build,query,batch,catalog}"""
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
|
@@ -14,17 +14,25 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 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)
|
| 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)
|
|
@@ -34,7 +42,38 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 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":
|
|
@@ -47,6 +86,9 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 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))
|
|
@@ -54,8 +96,17 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 54 |
if args.cmd == "batch":
|
| 55 |
from .build import batch
|
| 56 |
|
| 57 |
-
results = batch(
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
return 0
|
| 60 |
if args.cmd == "query":
|
| 61 |
from .query import main as qmain
|
|
@@ -63,12 +114,13 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 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
|
| 67 |
from .catalog import get_country
|
| 68 |
from .normalize import build_corpus, load_source
|
| 69 |
|
| 70 |
country = get_country(args.source)
|
| 71 |
-
|
|
|
|
| 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)
|
|
@@ -76,9 +128,69 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
return 0
|
| 83 |
return 1
|
| 84 |
|
|
|
|
| 1 |
+
"""python -m country_laws_ir {build,query,batch,catalog,normalize,package-raw}"""
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
|
|
|
| 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), country slug, or local pack dir")
|
| 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 |
+
help="Publish the packaged release to justicedao/ipfs_<slug>_laws_ir (requires HF_TOKEN)")
|
| 24 |
+
p_build.add_argument("--mode", default="auto", choices=["auto", "full", "delta"],
|
| 25 |
+
help="auto skips unchanged Hub revisions and reuses embeddings by entry_cid")
|
| 26 |
+
p_build.add_argument("--force", action="store_true", help="Ignore source fingerprint skip and reuse caches")
|
| 27 |
+
p_build.add_argument("--prior-dir", default=None, help="Prior GraphRAG release to delta against")
|
| 28 |
|
| 29 |
p_batch = sub.add_parser("batch")
|
| 30 |
p_batch.add_argument("--slugs", nargs="*", default=None)
|
| 31 |
p_batch.add_argument("--upload", action="store_true")
|
| 32 |
+
p_batch.add_argument("--no-skip-done", action="store_true",
|
| 33 |
+
help="Force a full rebuild of every country (ignore unchanged fingerprints)")
|
| 34 |
+
p_batch.add_argument("--mode", default="auto", choices=["auto", "full", "delta"])
|
| 35 |
+
p_batch.add_argument("--skip-vectors", action="store_true")
|
| 36 |
|
| 37 |
p_q = sub.add_parser("query")
|
| 38 |
p_q.add_argument("--local-dir", required=True)
|
|
|
|
| 42 |
p_norm.add_argument("--source-repo", "--source", dest="source", default="malta")
|
| 43 |
p_norm.add_argument("--out", default=None, help="Optional JSON report path")
|
| 44 |
|
| 45 |
+
p_cat = sub.add_parser("catalog")
|
| 46 |
+
p_cat.add_argument("--refresh", action="store_true",
|
| 47 |
+
help="List public endomorphosis/ipfs_*_laws datasets and persist new slugs")
|
| 48 |
+
|
| 49 |
+
p_cov = sub.add_parser("coverage", help="Compare endomorphosis sources vs justicedao GraphRAG releases")
|
| 50 |
+
p_cov.add_argument("--gaps", action="store_true",
|
| 51 |
+
help="Scan Hub for missing, stale, and incomplete IR (downloads manifests)")
|
| 52 |
+
p_cov.add_argument("--workers", type=int, default=8)
|
| 53 |
+
|
| 54 |
+
p_re = sub.add_parser(
|
| 55 |
+
"reindex",
|
| 56 |
+
help="Scan endomorphosis vs justicedao and incrementally rebuild stale/missing IR",
|
| 57 |
+
)
|
| 58 |
+
p_re.add_argument("--upload", action="store_true",
|
| 59 |
+
help="Publish rebuilt packs to justicedao (requires HF_TOKEN)")
|
| 60 |
+
p_re.add_argument("--slugs", nargs="*", default=None)
|
| 61 |
+
p_re.add_argument("--limit", type=int, default=None)
|
| 62 |
+
p_re.add_argument("--max-corpus-rows", type=int, default=20000,
|
| 63 |
+
help="Skip IR larger than this many rows (0 = no cap)")
|
| 64 |
+
p_re.add_argument("--skip-vectors", action="store_true")
|
| 65 |
+
p_re.add_argument("--workers", type=int, default=4)
|
| 66 |
+
p_re.add_argument("--mode", default="auto", choices=["auto", "full", "delta"])
|
| 67 |
+
|
| 68 |
+
p_raw = sub.add_parser("package-raw")
|
| 69 |
+
p_raw.add_argument("--slug", required=True, help="Country slug used in justicedao/ipfs_<slug>_laws_ir")
|
| 70 |
+
p_raw.add_argument("--instruments-dir", default=None,
|
| 71 |
+
help="Collector JSON directory (default: $LEGAL_CORPORA_ROOT/<iso-or-slug>/instruments)")
|
| 72 |
+
p_raw.add_argument("--iso", default=None, help="Collector ISO directory name if different from slug")
|
| 73 |
+
p_raw.add_argument("--out", default=None, help="Local pack directory (laws.parquet + pack_meta.json)")
|
| 74 |
+
p_raw.add_argument("--source-dataset", default=None,
|
| 75 |
+
help="Raw Hub id (default endomorphosis/ipfs_<slug>_laws)")
|
| 76 |
+
p_raw.add_argument("--prior-pack", default=None, help="Existing parquet pack to merge into")
|
| 77 |
|
| 78 |
args = ap.parse_args(argv)
|
| 79 |
if args.cmd == "build":
|
|
|
|
| 86 |
device=args.device,
|
| 87 |
neighbor_k=args.neighbor_k,
|
| 88 |
skip_vectors=args.skip_vectors,
|
| 89 |
+
mode=args.mode,
|
| 90 |
+
force=args.force,
|
| 91 |
+
prior_dir=Path(args.prior_dir) if args.prior_dir else None,
|
| 92 |
)
|
| 93 |
print(json.dumps({k: result[k] for k in result if k != "normalization"}, indent=2, default=str))
|
| 94 |
print(json.dumps({"normalization": result["normalization"]}, indent=2, default=str))
|
|
|
|
| 96 |
if args.cmd == "batch":
|
| 97 |
from .build import batch
|
| 98 |
|
| 99 |
+
results = batch(
|
| 100 |
+
slugs=args.slugs,
|
| 101 |
+
upload=args.upload,
|
| 102 |
+
skip_done=not args.no_skip_done,
|
| 103 |
+
mode=args.mode,
|
| 104 |
+
skip_vectors=args.skip_vectors,
|
| 105 |
+
)
|
| 106 |
+
print(json.dumps(
|
| 107 |
+
[{"country": r["country"], "out": r["out"], "skipped": r.get("skipped", False)} for r in results],
|
| 108 |
+
indent=2,
|
| 109 |
+
))
|
| 110 |
return 0
|
| 111 |
if args.cmd == "query":
|
| 112 |
from .query import main as qmain
|
|
|
|
| 114 |
argv2 = ["--local-dir", args.local_dir] + [a for a in args.rest if a != "--"]
|
| 115 |
return qmain(argv2)
|
| 116 |
if args.cmd == "normalize":
|
| 117 |
+
from .build import CACHE, REPORTS
|
| 118 |
from .catalog import get_country
|
| 119 |
from .normalize import build_corpus, load_source
|
| 120 |
|
| 121 |
country = get_country(args.source)
|
| 122 |
+
local = country.get("local_source_dir")
|
| 123 |
+
laws, articles, source_meta = load_source(local or country["repo"], CACHE)
|
| 124 |
corpus, report = build_corpus(laws, articles, source_meta)
|
| 125 |
out = Path(args.out) if args.out else REPORTS / f"{country['slug']}_normalization.json"
|
| 126 |
out.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
| 128 |
print(json.dumps({"out": str(out), "n_out": report["n_out"], "unit": report["unit"], "drops": report["drops"]}, indent=2))
|
| 129 |
return 0
|
| 130 |
if args.cmd == "catalog":
|
| 131 |
+
from .catalog import all_countries, refresh_from_hub
|
| 132 |
+
|
| 133 |
+
countries = refresh_from_hub() if args.refresh else all_countries()
|
| 134 |
+
print(json.dumps(
|
| 135 |
+
{"n": len(countries), "indexable": len([c for c in countries if c.get("indexable")]), "countries": countries},
|
| 136 |
+
indent=2,
|
| 137 |
+
))
|
| 138 |
+
return 0
|
| 139 |
+
if args.cmd == "coverage":
|
| 140 |
+
from .coverage import coverage_report, gap_report
|
| 141 |
+
|
| 142 |
+
report = gap_report(workers=args.workers) if args.gaps else coverage_report()
|
| 143 |
+
print(json.dumps(report, indent=2, default=str))
|
| 144 |
+
return 0
|
| 145 |
+
if args.cmd == "reindex":
|
| 146 |
+
from .build import reindex_from_gaps
|
| 147 |
|
| 148 |
+
cap = None if int(args.max_corpus_rows or 0) <= 0 else int(args.max_corpus_rows)
|
| 149 |
+
results = reindex_from_gaps(
|
| 150 |
+
upload=args.upload,
|
| 151 |
+
slugs=args.slugs or None,
|
| 152 |
+
limit=args.limit,
|
| 153 |
+
max_corpus_rows=cap,
|
| 154 |
+
skip_vectors=args.skip_vectors,
|
| 155 |
+
workers=args.workers,
|
| 156 |
+
mode=args.mode,
|
| 157 |
+
)
|
| 158 |
+
print(json.dumps(
|
| 159 |
+
[
|
| 160 |
+
{
|
| 161 |
+
"country": r.get("country"),
|
| 162 |
+
"skipped": r.get("skipped", False),
|
| 163 |
+
"out": r.get("out"),
|
| 164 |
+
"hub": (r.get("hub") or {}).get("url") if isinstance(r.get("hub"), dict) else r.get("hub"),
|
| 165 |
+
"error": r.get("error"),
|
| 166 |
+
"kind": (r.get("incremental") or {}).get("kind"),
|
| 167 |
+
"n_added": ((r.get("incremental") or {}).get("delta") or {}).get("n_added"),
|
| 168 |
+
"n_unchanged": ((r.get("incremental") or {}).get("delta") or {}).get("n_unchanged"),
|
| 169 |
+
}
|
| 170 |
+
for r in results
|
| 171 |
+
],
|
| 172 |
+
indent=2,
|
| 173 |
+
default=str,
|
| 174 |
+
))
|
| 175 |
+
return 1 if any(r.get("error") for r in results) else 0
|
| 176 |
+
if args.cmd == "package-raw":
|
| 177 |
+
from .build import RELEASES
|
| 178 |
+
from .raw_package import default_instruments_dir, package_instruments
|
| 179 |
+
|
| 180 |
+
instruments = (
|
| 181 |
+
Path(args.instruments_dir)
|
| 182 |
+
if args.instruments_dir
|
| 183 |
+
else default_instruments_dir(args.iso or args.slug)
|
| 184 |
+
)
|
| 185 |
+
out = Path(args.out) if args.out else RELEASES / "raw-packs" / args.slug
|
| 186 |
+
meta = package_instruments(
|
| 187 |
+
instruments_dir=instruments,
|
| 188 |
+
out=out,
|
| 189 |
+
slug=args.slug,
|
| 190 |
+
source_dataset=args.source_dataset,
|
| 191 |
+
prior_pack=Path(args.prior_pack) if args.prior_pack else None,
|
| 192 |
+
)
|
| 193 |
+
print(json.dumps(meta, indent=2, default=str))
|
| 194 |
return 0
|
| 195 |
return 1
|
| 196 |
|
country_laws_ir/auth.py
CHANGED
|
@@ -1,16 +1,38 @@
|
|
| 1 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
import os
|
|
|
|
| 6 |
|
| 7 |
|
| 8 |
def configure_hf() -> None:
|
| 9 |
-
"""
|
| 10 |
-
os.environ
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Hugging Face auth helpers.
|
| 2 |
+
|
| 3 |
+
Default reads stay anonymous. Gap scans and JusticeDAO uploads may use the
|
| 4 |
+
operator token from the Hugging Face cache file or the environment. The token
|
| 5 |
+
is never logged.
|
| 6 |
+
"""
|
| 7 |
|
| 8 |
from __future__ import annotations
|
| 9 |
|
| 10 |
import os
|
| 11 |
+
from pathlib import Path
|
| 12 |
|
| 13 |
|
| 14 |
def configure_hf() -> None:
|
| 15 |
+
"""Do not implicitly pick up ambient tokens for anonymous public reads."""
|
| 16 |
+
os.environ.setdefault("HF_HUB_DISABLE_IMPLICIT_TOKEN", "1")
|
|
|
|
| 17 |
|
| 18 |
|
| 19 |
def public_token() -> bool:
|
| 20 |
"""huggingface_hub `token=False` means anonymous (do not pick up env tokens)."""
|
| 21 |
return False
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def operator_token() -> str | bool:
|
| 25 |
+
"""Return a token for authenticated Hub reads/writes, or False if none."""
|
| 26 |
+
for key in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"):
|
| 27 |
+
value = (os.environ.get(key) or "").strip()
|
| 28 |
+
if value:
|
| 29 |
+
return value
|
| 30 |
+
path = Path.home() / ".cache" / "huggingface" / "token"
|
| 31 |
+
if path.is_file():
|
| 32 |
+
try:
|
| 33 |
+
value = path.read_text(encoding="utf-8").strip()
|
| 34 |
+
except OSError:
|
| 35 |
+
return False
|
| 36 |
+
if value:
|
| 37 |
+
return value
|
| 38 |
+
return False
|
country_laws_ir/build.py
CHANGED
|
@@ -1,7 +1,15 @@
|
|
| 1 |
-
"""End-to-end build: normalize →
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
|
|
|
|
|
|
| 5 |
import json
|
| 6 |
|
| 7 |
import pandas as pd
|
|
@@ -10,25 +18,34 @@ from datetime import datetime, timezone
|
|
| 10 |
from pathlib import Path
|
| 11 |
from typing import Any
|
| 12 |
|
| 13 |
-
from .
|
| 14 |
from .mem import MemAbort, checkpoint, log_mem
|
| 15 |
-
from .spill import
|
| 16 |
-
SQLITE_THRESHOLD,
|
| 17 |
-
build_bm25_tf_spill,
|
| 18 |
-
build_graph_from_neighbor_shards,
|
| 19 |
-
neighbors_via_sqlite,
|
| 20 |
-
should_use_sqlite,
|
| 21 |
-
spill_dir_for,
|
| 22 |
-
spill_pickle,
|
| 23 |
-
)
|
| 24 |
from .package import package_from_spill, package_release
|
| 25 |
from .catalog import get_country, indexable_countries, target_repo
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
from .normalize import build_corpus, load_source
|
| 28 |
from .auth import configure_hf
|
| 29 |
-
from .vectors import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
-
ROOT = Path("/
|
| 32 |
CACHE = ROOT / "cache"
|
| 33 |
RELEASES = ROOT / "releases"
|
| 34 |
REPORTS = ROOT / "reports"
|
|
@@ -47,6 +64,95 @@ def record_progress(event: dict[str, Any]) -> None:
|
|
| 47 |
f.write(json.dumps(event, ensure_ascii=False) + "\n")
|
| 48 |
|
| 49 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
def build_country(
|
| 51 |
source: str,
|
| 52 |
out: Path | None = None,
|
|
@@ -54,6 +160,10 @@ def build_country(
|
|
| 54 |
device: str = "cpu",
|
| 55 |
neighbor_k: int = 8,
|
| 56 |
skip_vectors: bool = False,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
) -> dict[str, Any]:
|
| 58 |
country = get_country(source)
|
| 59 |
if not country.get("indexable", True):
|
|
@@ -69,7 +179,9 @@ def build_country(
|
|
| 69 |
)
|
| 70 |
else None
|
| 71 |
)
|
| 72 |
-
_log(
|
|
|
|
|
|
|
| 73 |
configure_hf()
|
| 74 |
CACHE.mkdir(parents=True, exist_ok=True)
|
| 75 |
REPORTS.mkdir(parents=True, exist_ok=True)
|
|
@@ -78,6 +190,35 @@ def build_country(
|
|
| 78 |
f"source loaded laws={source_meta['n_laws_source']} "
|
| 79 |
f"articles={source_meta['n_articles_source']} rev={source_meta['source_revision']}"
|
| 80 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
corpus, norm_report = build_corpus(laws, articles, source_meta)
|
| 82 |
report_path = REPORTS / f"{country['slug']}_normalization.json"
|
| 83 |
report_path.write_text(json.dumps(norm_report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
|
@@ -93,6 +234,19 @@ def build_country(
|
|
| 93 |
|
| 94 |
import gc
|
| 95 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
n_docs = len(corpus)
|
| 97 |
spill = spill_dir_for(country["slug"], CACHE)
|
| 98 |
spill.mkdir(parents=True, exist_ok=True)
|
|
@@ -100,81 +254,63 @@ def build_country(
|
|
| 100 |
corpus.to_parquet(corpus_ckpt, index=False)
|
| 101 |
checkpoint("after_normalize", log=_log)
|
| 102 |
|
| 103 |
-
vector_blocker =
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
_log(f"vectors n={vectors['stats']['n_vectors']} shards={vectors['stats']['shard_count']}")
|
| 117 |
-
spill_pickle(spill / "vectors.pkl", vectors)
|
| 118 |
-
del embeddings, vectors
|
| 119 |
-
gc.collect()
|
| 120 |
-
checkpoint("vectors_spilled", log=_log)
|
| 121 |
-
except Exception as exc:
|
| 122 |
-
vector_blocker = f"embedding_failed: {exc}"
|
| 123 |
-
_log(f"vector embedding failed; writing stub ({exc})")
|
| 124 |
-
vectors = layout_stub_vectors(corpus, reason=vector_blocker)
|
| 125 |
-
spill_pickle(spill / "vectors.pkl", vectors)
|
| 126 |
-
del vectors
|
| 127 |
-
gc.collect()
|
| 128 |
-
else:
|
| 129 |
-
vector_blocker = "sentence-transformers/torch unavailable"
|
| 130 |
-
_log(f"vectors stub: {vector_blocker}")
|
| 131 |
-
vectors = layout_stub_vectors(corpus, reason=vector_blocker)
|
| 132 |
-
spill_pickle(spill / "vectors.pkl", vectors)
|
| 133 |
-
del vectors
|
| 134 |
-
gc.collect()
|
| 135 |
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
)
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
code_root
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
|
|
|
| 178 |
_log(f"packaged {out}")
|
| 179 |
result = {
|
| 180 |
"country": country["slug"],
|
|
@@ -187,6 +323,8 @@ def build_country(
|
|
| 187 |
"vector_blocker": vector_blocker,
|
| 188 |
"neighbor_via": neighbor_via,
|
| 189 |
"schema_version": manifest["schema_version"],
|
|
|
|
|
|
|
| 190 |
}
|
| 191 |
if upload:
|
| 192 |
from .upload import upload_release
|
|
@@ -204,25 +342,93 @@ def batch(
|
|
| 204 |
slugs: list[str] | None = None,
|
| 205 |
upload: bool = False,
|
| 206 |
skip_done: bool = True,
|
|
|
|
|
|
|
|
|
|
| 207 |
) -> list[dict[str, Any]]:
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
if rec.get("event") in {"uploaded", "built_local"} and rec.get("country"):
|
| 215 |
-
done.add(rec["country"])
|
| 216 |
targets = slugs or [c["slug"] for c in indexable_countries()]
|
| 217 |
if "malta" in targets:
|
| 218 |
targets = ["malta"] + [s for s in targets if s != "malta"]
|
| 219 |
results = []
|
|
|
|
| 220 |
for slug in targets:
|
| 221 |
-
|
| 222 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
try:
|
| 225 |
-
results.append(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
except Exception as exc:
|
| 227 |
_log(f"FAILED {slug}: {exc}")
|
| 228 |
record_progress(
|
|
@@ -233,5 +439,6 @@ def batch(
|
|
| 233 |
"traceback": traceback.format_exc(),
|
| 234 |
}
|
| 235 |
)
|
|
|
|
| 236 |
continue
|
| 237 |
return results
|
|
|
|
| 1 |
+
"""End-to-end build: normalize → incremental vectors → BM25 → graph → package.
|
| 2 |
+
|
| 3 |
+
Default mode is ``auto``: skip when the endomorphosis source revision is
|
| 4 |
+
unchanged, otherwise delta-refresh embeddings by ``entry_cid`` and rebuild
|
| 5 |
+
BM25/graph from the current corpus. Publication to ``justicedao/*`` is opt-in
|
| 6 |
+
via ``upload=True``.
|
| 7 |
+
"""
|
| 8 |
|
| 9 |
from __future__ import annotations
|
| 10 |
|
| 11 |
+
import os
|
| 12 |
+
|
| 13 |
import json
|
| 14 |
|
| 15 |
import pandas as pd
|
|
|
|
| 18 |
from pathlib import Path
|
| 19 |
from typing import Any
|
| 20 |
|
| 21 |
+
from .sparse import export_sparse_graphrag
|
| 22 |
from .mem import MemAbort, checkpoint, log_mem
|
| 23 |
+
from .spill import spill_dir_for, spill_pickle
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
from .package import package_from_spill, package_release
|
| 25 |
from .catalog import get_country, indexable_countries, target_repo
|
| 26 |
+
|
| 27 |
+
from .incremental import (
|
| 28 |
+
fetch_hub_prior,
|
| 29 |
+
load_embedding_cache,
|
| 30 |
+
load_prior_release,
|
| 31 |
+
load_release_vectors_by_cid,
|
| 32 |
+
merge_embedding_maps,
|
| 33 |
+
plan_rebuild,
|
| 34 |
+
save_embedding_cache,
|
| 35 |
+
)
|
| 36 |
from .normalize import build_corpus, load_source
|
| 37 |
from .auth import configure_hf
|
| 38 |
+
from .vectors import (
|
| 39 |
+
DIMENSION,
|
| 40 |
+
MODEL_NAME,
|
| 41 |
+
assemble_embeddings,
|
| 42 |
+
embeddings_available,
|
| 43 |
+
embeddings_by_cid,
|
| 44 |
+
layout_stub_vectors,
|
| 45 |
+
layout_vectors,
|
| 46 |
+
)
|
| 47 |
|
| 48 |
+
ROOT = Path(os.environ.get("COUNTRY_LAWS_IR_ROOT", str(Path.home() / ".ipfs_datasets" / "country-laws-ir")))
|
| 49 |
CACHE = ROOT / "cache"
|
| 50 |
RELEASES = ROOT / "releases"
|
| 51 |
REPORTS = ROOT / "reports"
|
|
|
|
| 64 |
f.write(json.dumps(event, ensure_ascii=False) + "\n")
|
| 65 |
|
| 66 |
|
| 67 |
+
def _prior_dir_for(
|
| 68 |
+
slug: str,
|
| 69 |
+
out: Path,
|
| 70 |
+
prior_dir: Path | None,
|
| 71 |
+
*,
|
| 72 |
+
fetch_hub: bool = True,
|
| 73 |
+
) -> Path | None:
|
| 74 |
+
if prior_dir is not None:
|
| 75 |
+
return Path(prior_dir)
|
| 76 |
+
if out.is_dir() and (out / "manifest.json").is_file():
|
| 77 |
+
return out
|
| 78 |
+
default = RELEASES / f"ipfs_{slug}_laws_ir"
|
| 79 |
+
if default.is_dir() and (default / "manifest.json").is_file() and default.resolve() != out.resolve():
|
| 80 |
+
return default
|
| 81 |
+
if not fetch_hub:
|
| 82 |
+
return None
|
| 83 |
+
hub = fetch_hub_prior(slug, cache_root=CACHE / "hub-ir")
|
| 84 |
+
if hub is not None:
|
| 85 |
+
_log(f"using justicedao prior {hub}")
|
| 86 |
+
return hub
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _encode_vectors(
|
| 90 |
+
*,
|
| 91 |
+
corpus: pd.DataFrame,
|
| 92 |
+
country_slug: str,
|
| 93 |
+
prior,
|
| 94 |
+
plan,
|
| 95 |
+
skip_vectors: bool,
|
| 96 |
+
device: str,
|
| 97 |
+
) -> tuple[dict[str, Any], str | None, dict[str, Any]]:
|
| 98 |
+
import gc
|
| 99 |
+
|
| 100 |
+
vector_report: dict[str, Any] = {"status": "stub"}
|
| 101 |
+
vector_blocker = None
|
| 102 |
+
if skip_vectors:
|
| 103 |
+
vectors = layout_stub_vectors(corpus, reason="skip_vectors flag")
|
| 104 |
+
return vectors, "skip_vectors", {"status": "stub", "reason": "skip_vectors"}
|
| 105 |
+
|
| 106 |
+
cid_cache_path = CACHE / "embeddings" / f"{country_slug}_by_cid.parquet"
|
| 107 |
+
prior_by_cid = {}
|
| 108 |
+
if plan.reuse_embeddings:
|
| 109 |
+
prior_by_cid = merge_embedding_maps(
|
| 110 |
+
load_embedding_cache(cid_cache_path),
|
| 111 |
+
None if prior is None else load_release_vectors_by_cid(prior.directory),
|
| 112 |
+
)
|
| 113 |
+
_log(f"embedding cache reused_cids={len(prior_by_cid)}")
|
| 114 |
+
try:
|
| 115 |
+
positional = CACHE / "embeddings" / f"{country_slug}.npy"
|
| 116 |
+
embeddings, vector_report = assemble_embeddings(
|
| 117 |
+
corpus,
|
| 118 |
+
prior_by_cid,
|
| 119 |
+
encode_missing=embeddings_available(),
|
| 120 |
+
device=device,
|
| 121 |
+
checkpoint_path=str(positional),
|
| 122 |
+
)
|
| 123 |
+
if (
|
| 124 |
+
vector_report.get("status") in {"stub_missing_encoder", "incomplete"}
|
| 125 |
+
and not int(vector_report.get("n_reused") or 0)
|
| 126 |
+
):
|
| 127 |
+
vector_blocker = vector_report.get("reason") or vector_report.get("status")
|
| 128 |
+
vectors = layout_stub_vectors(corpus, reason=str(vector_blocker))
|
| 129 |
+
return vectors, vector_blocker, vector_report
|
| 130 |
+
vectors = layout_vectors(corpus, embeddings)
|
| 131 |
+
if int(vector_report.get("n_reused") or 0) and vector_report.get("status") != "reused":
|
| 132 |
+
vectors["stats"]["status"] = "partial"
|
| 133 |
+
vectors["stats"]["n_reused"] = int(vector_report.get("n_reused") or 0)
|
| 134 |
+
vectors["stats"]["n_missing"] = int(vector_report.get("n_missing") or 0)
|
| 135 |
+
vector_blocker = vector_report.get("reason") or vector_report.get("status")
|
| 136 |
+
save_embedding_cache(
|
| 137 |
+
cid_cache_path,
|
| 138 |
+
merge_embedding_maps(prior_by_cid, embeddings_by_cid(corpus, embeddings)),
|
| 139 |
+
model_name=MODEL_NAME,
|
| 140 |
+
dimension=DIMENSION,
|
| 141 |
+
)
|
| 142 |
+
del embeddings
|
| 143 |
+
gc.collect()
|
| 144 |
+
_log(
|
| 145 |
+
f"vectors n={vectors['stats']['n_vectors']} shards={vectors['stats']['shard_count']} "
|
| 146 |
+
f"reused={vector_report.get('n_reused')} encoded={vector_report.get('n_encoded')}"
|
| 147 |
+
)
|
| 148 |
+
return vectors, None, vector_report
|
| 149 |
+
except Exception as exc:
|
| 150 |
+
vector_blocker = f"embedding_failed: {exc}"
|
| 151 |
+
_log(f"vector embedding failed; writing stub ({exc})")
|
| 152 |
+
vectors = layout_stub_vectors(corpus, reason=vector_blocker)
|
| 153 |
+
return vectors, vector_blocker, {"status": "failed", "reason": str(exc)}
|
| 154 |
+
|
| 155 |
+
|
| 156 |
def build_country(
|
| 157 |
source: str,
|
| 158 |
out: Path | None = None,
|
|
|
|
| 160 |
device: str = "cpu",
|
| 161 |
neighbor_k: int = 8,
|
| 162 |
skip_vectors: bool = False,
|
| 163 |
+
mode: str = "auto",
|
| 164 |
+
force: bool = False,
|
| 165 |
+
prior_dir: Path | None = None,
|
| 166 |
+
fetch_hub_prior_ir: bool = True,
|
| 167 |
) -> dict[str, Any]:
|
| 168 |
country = get_country(source)
|
| 169 |
if not country.get("indexable", True):
|
|
|
|
| 179 |
)
|
| 180 |
else None
|
| 181 |
)
|
| 182 |
+
_log(
|
| 183 |
+
f"build start {repo} -> {out} (upload={upload} mode={mode} force={force}) local={local_dir}"
|
| 184 |
+
)
|
| 185 |
configure_hf()
|
| 186 |
CACHE.mkdir(parents=True, exist_ok=True)
|
| 187 |
REPORTS.mkdir(parents=True, exist_ok=True)
|
|
|
|
| 190 |
f"source loaded laws={source_meta['n_laws_source']} "
|
| 191 |
f"articles={source_meta['n_articles_source']} rev={source_meta['source_revision']}"
|
| 192 |
)
|
| 193 |
+
prior = load_prior_release(
|
| 194 |
+
_prior_dir_for(
|
| 195 |
+
country["slug"],
|
| 196 |
+
out,
|
| 197 |
+
prior_dir,
|
| 198 |
+
fetch_hub=fetch_hub_prior_ir,
|
| 199 |
+
)
|
| 200 |
+
)
|
| 201 |
+
plan = plan_rebuild(
|
| 202 |
+
mode=mode, source_meta=source_meta, prior=prior, force=force
|
| 203 |
+
)
|
| 204 |
+
if plan.skip_build:
|
| 205 |
+
_log(f"skip unchanged {country['slug']} rev={plan.source_revision}")
|
| 206 |
+
result = {
|
| 207 |
+
"country": country["slug"],
|
| 208 |
+
"source": repo,
|
| 209 |
+
"source_revision": source_meta["source_revision"],
|
| 210 |
+
"out": str(out),
|
| 211 |
+
"target_hub_id": target_repo(country["slug"]),
|
| 212 |
+
"skipped": True,
|
| 213 |
+
"incremental": plan.to_dict(),
|
| 214 |
+
"normalization": {"n_out": plan.delta.current_count if plan.delta else 0},
|
| 215 |
+
"vector_blocker": None,
|
| 216 |
+
"neighbor_via": None,
|
| 217 |
+
"schema_version": "country-laws-ir-graphrag/v1",
|
| 218 |
+
}
|
| 219 |
+
record_progress({"event": "skipped_unchanged", **{k: v for k, v in result.items() if k != "normalization"}})
|
| 220 |
+
return result
|
| 221 |
+
|
| 222 |
corpus, norm_report = build_corpus(laws, articles, source_meta)
|
| 223 |
report_path = REPORTS / f"{country['slug']}_normalization.json"
|
| 224 |
report_path.write_text(json.dumps(norm_report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
|
|
|
| 234 |
|
| 235 |
import gc
|
| 236 |
|
| 237 |
+
plan = plan_rebuild(
|
| 238 |
+
mode=mode,
|
| 239 |
+
source_meta=source_meta,
|
| 240 |
+
prior=prior,
|
| 241 |
+
current_corpus=corpus,
|
| 242 |
+
force=force,
|
| 243 |
+
)
|
| 244 |
+
_log(
|
| 245 |
+
f"rebuild kind={plan.kind.value} reuse_embeddings={plan.reuse_embeddings} "
|
| 246 |
+
f"added={0 if plan.delta is None else plan.delta.n_added} "
|
| 247 |
+
f"removed={0 if plan.delta is None else plan.delta.n_removed}"
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
n_docs = len(corpus)
|
| 251 |
spill = spill_dir_for(country["slug"], CACHE)
|
| 252 |
spill.mkdir(parents=True, exist_ok=True)
|
|
|
|
| 254 |
corpus.to_parquet(corpus_ckpt, index=False)
|
| 255 |
checkpoint("after_normalize", log=_log)
|
| 256 |
|
| 257 |
+
vectors, vector_blocker, vector_report = _encode_vectors(
|
| 258 |
+
corpus=corpus,
|
| 259 |
+
country_slug=country["slug"],
|
| 260 |
+
prior=prior,
|
| 261 |
+
plan=plan,
|
| 262 |
+
skip_vectors=skip_vectors,
|
| 263 |
+
device=device,
|
| 264 |
+
)
|
| 265 |
+
spill_pickle(spill / "vectors.pkl", vectors)
|
| 266 |
+
del vectors
|
| 267 |
+
gc.collect()
|
| 268 |
+
checkpoint("vectors_spilled", log=_log)
|
| 269 |
+
extra_manifest = {"incremental": {**plan.to_dict(), "vectors": vector_report}}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 270 |
|
| 271 |
+
neighbor_via = "hf_graphrag"
|
| 272 |
+
if out.exists():
|
| 273 |
+
import shutil as _shutil
|
| 274 |
+
|
| 275 |
+
_shutil.rmtree(out)
|
| 276 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 277 |
+
_log(f"sparse GraphRAG via hf_graphrag.bm25/graph parquet builders n={n_docs}")
|
| 278 |
+
sparse_report = export_sparse_graphrag(corpus, out)
|
| 279 |
+
extra_manifest["sparse"] = sparse_report
|
| 280 |
+
with open(spill / "vectors.pkl", "rb") as _vf:
|
| 281 |
+
import pickle as _pickle
|
| 282 |
+
|
| 283 |
+
vectors = _pickle.load(_vf)
|
| 284 |
+
dummy_bm25 = {
|
| 285 |
+
"documents": pd.DataFrame(),
|
| 286 |
+
"postings": pd.DataFrame(),
|
| 287 |
+
"stats": (sparse_report.get("bm25") or {}).get("bm25")
|
| 288 |
+
or (sparse_report.get("bm25") or {}),
|
| 289 |
+
}
|
| 290 |
+
dummy_graph = {
|
| 291 |
+
"nodes": pd.DataFrame(),
|
| 292 |
+
"edges": pd.DataFrame(),
|
| 293 |
+
"incoming": pd.DataFrame(),
|
| 294 |
+
"outgoing": pd.DataFrame(),
|
| 295 |
+
"stats": sparse_report.get("graph") or {},
|
| 296 |
+
}
|
| 297 |
+
code_root = Path(__file__).resolve().parent.parent
|
| 298 |
+
manifest = package_release(
|
| 299 |
+
out,
|
| 300 |
+
corpus,
|
| 301 |
+
dummy_bm25,
|
| 302 |
+
dummy_graph,
|
| 303 |
+
vectors,
|
| 304 |
+
source_meta,
|
| 305 |
+
country,
|
| 306 |
+
code_root,
|
| 307 |
+
normalization_report=norm_report,
|
| 308 |
+
extra_manifest=extra_manifest,
|
| 309 |
+
wipe=False,
|
| 310 |
+
skip_bm25_graph=True,
|
| 311 |
+
)
|
| 312 |
+
del corpus, vectors
|
| 313 |
+
gc.collect()
|
| 314 |
_log(f"packaged {out}")
|
| 315 |
result = {
|
| 316 |
"country": country["slug"],
|
|
|
|
| 323 |
"vector_blocker": vector_blocker,
|
| 324 |
"neighbor_via": neighbor_via,
|
| 325 |
"schema_version": manifest["schema_version"],
|
| 326 |
+
"skipped": False,
|
| 327 |
+
"incremental": extra_manifest["incremental"],
|
| 328 |
}
|
| 329 |
if upload:
|
| 330 |
from .upload import upload_release
|
|
|
|
| 342 |
slugs: list[str] | None = None,
|
| 343 |
upload: bool = False,
|
| 344 |
skip_done: bool = True,
|
| 345 |
+
mode: str = "auto",
|
| 346 |
+
force: bool = False,
|
| 347 |
+
skip_vectors: bool = False,
|
| 348 |
) -> list[dict[str, Any]]:
|
| 349 |
+
"""Build every indexable country. Unchanged Hub revisions are skipped in auto mode.
|
| 350 |
+
|
| 351 |
+
``skip_done`` is kept for compatibility: it no longer skips a country whose
|
| 352 |
+
source revision changed. Pass ``force=True`` (or ``--no-skip-done``) to
|
| 353 |
+
rebuild regardless of CID overlap.
|
| 354 |
+
"""
|
|
|
|
|
|
|
| 355 |
targets = slugs or [c["slug"] for c in indexable_countries()]
|
| 356 |
if "malta" in targets:
|
| 357 |
targets = ["malta"] + [s for s in targets if s != "malta"]
|
| 358 |
results = []
|
| 359 |
+
rebuild_force = force or not skip_done
|
| 360 |
for slug in targets:
|
| 361 |
+
try:
|
| 362 |
+
results.append(
|
| 363 |
+
build_country(
|
| 364 |
+
slug,
|
| 365 |
+
upload=upload,
|
| 366 |
+
mode=mode,
|
| 367 |
+
force=rebuild_force,
|
| 368 |
+
skip_vectors=skip_vectors,
|
| 369 |
+
)
|
| 370 |
+
)
|
| 371 |
+
except Exception as exc:
|
| 372 |
+
_log(f"FAILED {slug}: {exc}")
|
| 373 |
+
record_progress(
|
| 374 |
+
{
|
| 375 |
+
"event": "failed",
|
| 376 |
+
"country": slug,
|
| 377 |
+
"error": str(exc),
|
| 378 |
+
"traceback": traceback.format_exc(),
|
| 379 |
+
}
|
| 380 |
+
)
|
| 381 |
continue
|
| 382 |
+
return results
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def reindex_from_gaps(
|
| 386 |
+
*,
|
| 387 |
+
upload: bool = False,
|
| 388 |
+
slugs: list[str] | None = None,
|
| 389 |
+
limit: int | None = None,
|
| 390 |
+
max_corpus_rows: int | None = 20_000,
|
| 391 |
+
skip_vectors: bool = False,
|
| 392 |
+
workers: int = 4,
|
| 393 |
+
mode: str = "auto",
|
| 394 |
+
) -> list[dict[str, Any]]:
|
| 395 |
+
"""Scan Hub gaps and incrementally rebuild stale/missing country IR.
|
| 396 |
+
|
| 397 |
+
Default cap skips huge corpora (Finland, Dominican Republic). Pass
|
| 398 |
+
``max_corpus_rows=None`` to include them.
|
| 399 |
+
"""
|
| 400 |
+
from .coverage import gap_report
|
| 401 |
+
|
| 402 |
+
if slugs is None:
|
| 403 |
+
report = gap_report(workers=workers)
|
| 404 |
+
rows = [c for c in report["countries"] if c.get("rebuild")]
|
| 405 |
+
rows.sort(key=lambda r: int(r.get("corpus_rows") or 0))
|
| 406 |
+
if max_corpus_rows is not None:
|
| 407 |
+
rows = [
|
| 408 |
+
r
|
| 409 |
+
for r in rows
|
| 410 |
+
if int(r.get("corpus_rows") or 0) <= int(max_corpus_rows)
|
| 411 |
+
]
|
| 412 |
+
if limit is not None:
|
| 413 |
+
rows = rows[: int(limit)]
|
| 414 |
+
slugs = [str(r["slug"]) for r in rows]
|
| 415 |
+
_log(
|
| 416 |
+
f"reindex targets n={len(slugs)} "
|
| 417 |
+
f"(from scan rebuild={len(report.get('rebuild') or [])})"
|
| 418 |
+
)
|
| 419 |
+
results: list[dict[str, Any]] = []
|
| 420 |
+
for slug in slugs:
|
| 421 |
+
_log(f"reindex start {slug}")
|
| 422 |
try:
|
| 423 |
+
results.append(
|
| 424 |
+
build_country(
|
| 425 |
+
slug,
|
| 426 |
+
upload=upload,
|
| 427 |
+
mode=mode,
|
| 428 |
+
skip_vectors=skip_vectors,
|
| 429 |
+
fetch_hub_prior_ir=True,
|
| 430 |
+
)
|
| 431 |
+
)
|
| 432 |
except Exception as exc:
|
| 433 |
_log(f"FAILED {slug}: {exc}")
|
| 434 |
record_progress(
|
|
|
|
| 439 |
"traceback": traceback.format_exc(),
|
| 440 |
}
|
| 441 |
)
|
| 442 |
+
results.append({"country": slug, "skipped": False, "error": str(exc)})
|
| 443 |
continue
|
| 444 |
return results
|
country_laws_ir/catalog.py
CHANGED
|
@@ -2,15 +2,39 @@
|
|
| 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},
|
|
@@ -88,6 +112,54 @@ COUNTRIES: list[dict[str, Any]] = [
|
|
| 88 |
]
|
| 89 |
|
| 90 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
def get_country(source: str) -> dict[str, Any]:
|
| 92 |
source = source.strip()
|
| 93 |
# Local filtered pack: directory with data/laws.parquet (+ optional pack_meta.json)
|
|
@@ -133,7 +205,7 @@ def get_country(source: str) -> dict[str, Any]:
|
|
| 133 |
if "/" in source:
|
| 134 |
slug = source.rsplit("/", 1)[-1]
|
| 135 |
slug = slug.removeprefix("ipfs_").removesuffix("_laws").removesuffix("-ir")
|
| 136 |
-
for row in
|
| 137 |
if row["slug"] == slug or row["repo"] == source or row["repo"].endswith("/" + source):
|
| 138 |
return dict(row)
|
| 139 |
if source.startswith("endomorphosis/ipfs_") and source.endswith("_laws"):
|
|
@@ -143,20 +215,20 @@ def get_country(source: str) -> dict[str, Any]:
|
|
| 143 |
"repo": source,
|
| 144 |
"name": inferred.replace("_", " ").title(),
|
| 145 |
"indexable": inferred not in EXCLUDED_SLUGS,
|
| 146 |
-
"skip_reason":
|
| 147 |
}
|
| 148 |
raise KeyError(f"Unknown country-law source: {source}")
|
| 149 |
|
| 150 |
|
| 151 |
def indexable_countries() -> list[dict[str, Any]]:
|
| 152 |
-
return [c for c in
|
| 153 |
|
| 154 |
|
| 155 |
def target_repo(slug: str) -> str:
|
| 156 |
return f"justicedao/ipfs_{slug}_laws_ir"
|
| 157 |
|
| 158 |
|
| 159 |
-
def refresh_from_hub() -> list[dict[str, Any]]:
|
| 160 |
"""Anonymous Hub listing of public endomorphosis/ipfs_*_laws datasets."""
|
| 161 |
from huggingface_hub import HfApi
|
| 162 |
|
|
@@ -175,9 +247,10 @@ def refresh_from_hub() -> list[dict[str, Any]]:
|
|
| 175 |
"repo": ds_id,
|
| 176 |
"name": slug.replace("_", " ").title(),
|
| 177 |
"indexable": slug not in EXCLUDED_SLUGS,
|
| 178 |
-
"skip_reason": (
|
| 179 |
-
"incomplete Wayback harvest" if slug in EXCLUDED_SLUGS else None
|
| 180 |
-
),
|
| 181 |
})
|
| 182 |
found.sort(key=lambda r: r["slug"])
|
| 183 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
The static ``COUNTRIES`` list is the fail-closed baseline. ``refresh_from_hub``
|
| 7 |
+
persists a sidecar cache of newly listed Hub datasets so incremental scrapes
|
| 8 |
+
of additional jurisdictions are indexable without a code change.
|
| 9 |
"""
|
| 10 |
|
| 11 |
from __future__ import annotations
|
| 12 |
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
from pathlib import Path
|
| 16 |
from typing import Any
|
| 17 |
|
| 18 |
+
EXCLUDED_SLUGS = {"belgium", "portugal", "lithuania", "ghana"}
|
| 19 |
EXCLUDED_REPOS = {f"endomorphosis/ipfs_{s}_laws" for s in EXCLUDED_SLUGS}
|
| 20 |
|
| 21 |
+
_SKIP_REASONS = {
|
| 22 |
+
"belgium": "incomplete Wayback harvest (Justel / Moniteur belge archive shard)",
|
| 23 |
+
"portugal": "incomplete Wayback harvest (Diário da República archive shard)",
|
| 24 |
+
"lithuania": "incomplete Wayback harvest (e-TAR archive shard)",
|
| 25 |
+
"ghana": "thin scrape; Act PDF path blocked by robots",
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def catalog_cache_path() -> Path:
|
| 30 |
+
root = Path(
|
| 31 |
+
os.environ.get(
|
| 32 |
+
"COUNTRY_LAWS_IR_ROOT",
|
| 33 |
+
str(Path.home() / ".ipfs_datasets" / "country-laws-ir"),
|
| 34 |
+
)
|
| 35 |
+
)
|
| 36 |
+
return root / "catalog_cache.json"
|
| 37 |
+
|
| 38 |
# Hub listing as of 2026-09-03. Refresh via `python -m country_laws_ir catalog --refresh`.
|
| 39 |
COUNTRIES: list[dict[str, Any]] = [
|
| 40 |
{"slug": "argentina", "repo": "endomorphosis/ipfs_argentina_laws", "name": "Argentina", "indexable": True},
|
|
|
|
| 112 |
]
|
| 113 |
|
| 114 |
|
| 115 |
+
def load_cached_countries() -> list[dict[str, Any]]:
|
| 116 |
+
path = catalog_cache_path()
|
| 117 |
+
if not path.is_file():
|
| 118 |
+
return []
|
| 119 |
+
try:
|
| 120 |
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
| 121 |
+
except Exception:
|
| 122 |
+
return []
|
| 123 |
+
rows = payload.get("countries") if isinstance(payload, dict) else payload
|
| 124 |
+
if not isinstance(rows, list):
|
| 125 |
+
return []
|
| 126 |
+
out: list[dict[str, Any]] = []
|
| 127 |
+
for row in rows:
|
| 128 |
+
if isinstance(row, dict) and row.get("slug") and row.get("repo"):
|
| 129 |
+
out.append(dict(row))
|
| 130 |
+
return out
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def persist_catalog(countries: list[dict[str, Any]], path: Path | None = None) -> Path:
|
| 134 |
+
dest = path or catalog_cache_path()
|
| 135 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 136 |
+
payload = {
|
| 137 |
+
"n": len(countries),
|
| 138 |
+
"indexable": sum(1 for c in countries if c.get("indexable")),
|
| 139 |
+
"countries": countries,
|
| 140 |
+
}
|
| 141 |
+
dest.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
| 142 |
+
return dest
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def merge_country_rows(
|
| 146 |
+
baseline: list[dict[str, Any]],
|
| 147 |
+
extra: list[dict[str, Any]],
|
| 148 |
+
) -> list[dict[str, Any]]:
|
| 149 |
+
"""Static catalog wins on slug; Hub extras fill gaps."""
|
| 150 |
+
by_slug = {str(row["slug"]): dict(row) for row in baseline if row.get("slug")}
|
| 151 |
+
for row in extra:
|
| 152 |
+
slug = str(row.get("slug") or "")
|
| 153 |
+
if not slug or slug in by_slug:
|
| 154 |
+
continue
|
| 155 |
+
by_slug[slug] = dict(row)
|
| 156 |
+
return [by_slug[k] for k in sorted(by_slug)]
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def all_countries() -> list[dict[str, Any]]:
|
| 160 |
+
return merge_country_rows(COUNTRIES, load_cached_countries())
|
| 161 |
+
|
| 162 |
+
|
| 163 |
def get_country(source: str) -> dict[str, Any]:
|
| 164 |
source = source.strip()
|
| 165 |
# Local filtered pack: directory with data/laws.parquet (+ optional pack_meta.json)
|
|
|
|
| 205 |
if "/" in source:
|
| 206 |
slug = source.rsplit("/", 1)[-1]
|
| 207 |
slug = slug.removeprefix("ipfs_").removesuffix("_laws").removesuffix("-ir")
|
| 208 |
+
for row in all_countries():
|
| 209 |
if row["slug"] == slug or row["repo"] == source or row["repo"].endswith("/" + source):
|
| 210 |
return dict(row)
|
| 211 |
if source.startswith("endomorphosis/ipfs_") and source.endswith("_laws"):
|
|
|
|
| 215 |
"repo": source,
|
| 216 |
"name": inferred.replace("_", " ").title(),
|
| 217 |
"indexable": inferred not in EXCLUDED_SLUGS,
|
| 218 |
+
"skip_reason": _SKIP_REASONS.get(inferred),
|
| 219 |
}
|
| 220 |
raise KeyError(f"Unknown country-law source: {source}")
|
| 221 |
|
| 222 |
|
| 223 |
def indexable_countries() -> list[dict[str, Any]]:
|
| 224 |
+
return [c for c in all_countries() if c.get("indexable")]
|
| 225 |
|
| 226 |
|
| 227 |
def target_repo(slug: str) -> str:
|
| 228 |
return f"justicedao/ipfs_{slug}_laws_ir"
|
| 229 |
|
| 230 |
|
| 231 |
+
def refresh_from_hub(*, persist: bool = True) -> list[dict[str, Any]]:
|
| 232 |
"""Anonymous Hub listing of public endomorphosis/ipfs_*_laws datasets."""
|
| 233 |
from huggingface_hub import HfApi
|
| 234 |
|
|
|
|
| 247 |
"repo": ds_id,
|
| 248 |
"name": slug.replace("_", " ").title(),
|
| 249 |
"indexable": slug not in EXCLUDED_SLUGS,
|
| 250 |
+
"skip_reason": _SKIP_REASONS.get(slug),
|
|
|
|
|
|
|
| 251 |
})
|
| 252 |
found.sort(key=lambda r: r["slug"])
|
| 253 |
+
merged = merge_country_rows(COUNTRIES, found)
|
| 254 |
+
if persist:
|
| 255 |
+
persist_catalog(merged)
|
| 256 |
+
return merged
|
country_laws_ir/cidutil.py
CHANGED
|
@@ -59,6 +59,27 @@ def cid_v1_raw_sha256(data: bytes) -> str:
|
|
| 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 |
|
|
|
|
| 59 |
return "b" + _b32encode(cid_bytes)
|
| 60 |
|
| 61 |
|
| 62 |
+
def sha256_key_to_cidv1(value: str) -> str:
|
| 63 |
+
"""Turn a bare/prefixed SHA-256 routing key into ``bafkrei…`` CIDv1.
|
| 64 |
+
|
| 65 |
+
GraphRAG locators must not use hex digests as ``entry_cid`` / ``node_cid``.
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
text = str(value or "").strip()
|
| 69 |
+
if text.startswith("bafkrei"):
|
| 70 |
+
return text
|
| 71 |
+
hex_part = text[7:71] if text.lower().startswith("sha256:") else text[:64]
|
| 72 |
+
rest = text[71:] if text.lower().startswith("sha256:") else text[64:]
|
| 73 |
+
if len(hex_part) != 64:
|
| 74 |
+
return text
|
| 75 |
+
try:
|
| 76 |
+
digest = bytes.fromhex(hex_part)
|
| 77 |
+
except ValueError:
|
| 78 |
+
return text
|
| 79 |
+
cid_bytes = bytes([0x01, 0x55, 0x12, 0x20]) + digest
|
| 80 |
+
return "b" + _b32encode(cid_bytes) + rest
|
| 81 |
+
|
| 82 |
+
|
| 83 |
def cid_of_json(obj: Any) -> str:
|
| 84 |
return cid_v1_raw_sha256(canonical_json_bytes(obj))
|
| 85 |
|
country_laws_ir/coverage.py
ADDED
|
@@ -0,0 +1,452 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Compare endomorphosis raw sources against justicedao GraphRAG releases.
|
| 2 |
+
|
| 3 |
+
Gap kinds
|
| 4 |
+
---------
|
| 5 |
+
* missing — no JusticeDAO IR (and no local pack)
|
| 6 |
+
* unpublished — local IR exists, Hub IR does not
|
| 7 |
+
* stale — Hub/local IR source revision does not match current endomorphosis SHA
|
| 8 |
+
* incomplete — missing corpus/BM25/graph, empty corpus, or source has no laws
|
| 9 |
+
* stub_vectors — IR is otherwise current but embeddings were stubbed
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import json
|
| 15 |
+
import time
|
| 16 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
from typing import Any, Mapping
|
| 19 |
+
|
| 20 |
+
from .catalog import EXCLUDED_SLUGS, all_countries, target_repo
|
| 21 |
+
|
| 22 |
+
ALIAS_TO_CANONICAL = {
|
| 23 |
+
"dominican_republic": "dominicanrepublic",
|
| 24 |
+
"el_salvador": "elsalvador",
|
| 25 |
+
"north_korea": "northkorea",
|
| 26 |
+
"papua_new_guinea": "papuanewguinea",
|
| 27 |
+
"san_marino": "sanmarino",
|
| 28 |
+
"trinidad_and_tobago": "trinidad",
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _slug_from_source(dataset_id: str) -> str | None:
|
| 33 |
+
if not dataset_id.startswith("endomorphosis/ipfs_") or not dataset_id.endswith("_laws"):
|
| 34 |
+
return None
|
| 35 |
+
return dataset_id.split("ipfs_", 1)[1].removesuffix("_laws")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _slug_from_ir(dataset_id: str) -> str | None:
|
| 39 |
+
if not dataset_id.startswith("justicedao/ipfs_") or not dataset_id.endswith("_laws_ir"):
|
| 40 |
+
return None
|
| 41 |
+
return dataset_id.split("ipfs_", 1)[1].removesuffix("_laws_ir")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def canonical_slug(slug: str) -> str:
|
| 45 |
+
return ALIAS_TO_CANONICAL.get(slug, slug)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def list_hub_slugs(*, author: str, kind: str) -> list[str]:
|
| 49 |
+
from huggingface_hub import HfApi
|
| 50 |
+
|
| 51 |
+
from .auth import configure_hf, operator_token, public_token
|
| 52 |
+
|
| 53 |
+
configure_hf()
|
| 54 |
+
token = operator_token() or public_token()
|
| 55 |
+
api = HfApi(token=token)
|
| 56 |
+
out: list[str] = []
|
| 57 |
+
for ds in api.list_datasets(author=author):
|
| 58 |
+
slug = _slug_from_source(ds.id) if kind == "source" else _slug_from_ir(ds.id)
|
| 59 |
+
if slug:
|
| 60 |
+
out.append(slug)
|
| 61 |
+
return sorted(set(out))
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def local_release_slugs(releases_dir: Path) -> list[str]:
|
| 65 |
+
if not releases_dir.is_dir():
|
| 66 |
+
return []
|
| 67 |
+
found: list[str] = []
|
| 68 |
+
for path in sorted(releases_dir.glob("ipfs_*_laws_ir")):
|
| 69 |
+
if (path / "manifest.json").is_file():
|
| 70 |
+
slug = path.name.removeprefix("ipfs_").removesuffix("_laws_ir")
|
| 71 |
+
found.append(slug)
|
| 72 |
+
return found
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
IR_FAMILY_PREFIXES = (
|
| 76 |
+
("data/corpus/", "ir_missing_corpus"),
|
| 77 |
+
("data/bm25/", "ir_missing_bm25"),
|
| 78 |
+
("data/graph/", "ir_missing_graph"),
|
| 79 |
+
)
|
| 80 |
+
STUB_VECTOR_STATUSES = {"stub", "stub_missing_encoder", "incomplete"}
|
| 81 |
+
TINY_LAWS_BYTES = 1024
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def classify_gap(
|
| 85 |
+
*,
|
| 86 |
+
excluded: bool = False,
|
| 87 |
+
alias: bool = False,
|
| 88 |
+
source_has_laws: bool = True,
|
| 89 |
+
source_laws_bytes: int | None = None,
|
| 90 |
+
source_revision: str | None = None,
|
| 91 |
+
ir_files: list[str] | None = None,
|
| 92 |
+
ir_source_revision: str | None = None,
|
| 93 |
+
ir_corpus_rows: int | None = None,
|
| 94 |
+
vector_status: str | None = None,
|
| 95 |
+
local_only: bool = False,
|
| 96 |
+
local_source_revision: str | None = None,
|
| 97 |
+
) -> dict[str, Any]:
|
| 98 |
+
"""Pure classifier for missing / stale / incomplete country IR."""
|
| 99 |
+
issues: list[str] = []
|
| 100 |
+
if alias:
|
| 101 |
+
return {"status": "alias", "issues": issues, "rebuild": False, "publish": False}
|
| 102 |
+
if excluded:
|
| 103 |
+
return {"status": "excluded", "issues": issues, "rebuild": False, "publish": False}
|
| 104 |
+
|
| 105 |
+
if not source_has_laws:
|
| 106 |
+
issues.append("source_missing_laws")
|
| 107 |
+
if (
|
| 108 |
+
source_laws_bytes is not None
|
| 109 |
+
and source_laws_bytes >= 0
|
| 110 |
+
and source_laws_bytes < TINY_LAWS_BYTES
|
| 111 |
+
):
|
| 112 |
+
issues.append("source_laws_tiny")
|
| 113 |
+
|
| 114 |
+
if ir_files is None:
|
| 115 |
+
issues.append("missing_ir")
|
| 116 |
+
else:
|
| 117 |
+
names = set(ir_files)
|
| 118 |
+
if "manifest.json" not in names:
|
| 119 |
+
issues.append("ir_missing_manifest")
|
| 120 |
+
for prefix, issue in IR_FAMILY_PREFIXES:
|
| 121 |
+
if not any(name.startswith(prefix) for name in names):
|
| 122 |
+
issues.append(issue)
|
| 123 |
+
if ir_corpus_rows is not None and int(ir_corpus_rows) <= 0:
|
| 124 |
+
issues.append("ir_empty_corpus")
|
| 125 |
+
if (
|
| 126 |
+
source_revision
|
| 127 |
+
and ir_source_revision
|
| 128 |
+
and str(source_revision) != str(ir_source_revision)
|
| 129 |
+
):
|
| 130 |
+
issues.append("stale_source_revision")
|
| 131 |
+
if vector_status in STUB_VECTOR_STATUSES:
|
| 132 |
+
issues.append("ir_stub_vectors")
|
| 133 |
+
|
| 134 |
+
structural = {
|
| 135 |
+
"source_missing_laws",
|
| 136 |
+
"source_laws_tiny",
|
| 137 |
+
"ir_missing_manifest",
|
| 138 |
+
"ir_missing_corpus",
|
| 139 |
+
"ir_missing_bm25",
|
| 140 |
+
"ir_missing_graph",
|
| 141 |
+
"ir_empty_corpus",
|
| 142 |
+
}
|
| 143 |
+
issue_set = set(issues)
|
| 144 |
+
if "missing_ir" in issue_set:
|
| 145 |
+
status = "unpublished" if local_only else "missing"
|
| 146 |
+
elif "stale_source_revision" in issue_set:
|
| 147 |
+
status = "stale"
|
| 148 |
+
elif issue_set & structural:
|
| 149 |
+
status = "incomplete"
|
| 150 |
+
elif issue_set == {"ir_stub_vectors"}:
|
| 151 |
+
status = "stub_vectors"
|
| 152 |
+
elif not issues:
|
| 153 |
+
status = "current"
|
| 154 |
+
else:
|
| 155 |
+
status = "incomplete"
|
| 156 |
+
|
| 157 |
+
local_current = bool(
|
| 158 |
+
source_revision
|
| 159 |
+
and local_source_revision
|
| 160 |
+
and str(source_revision) == str(local_source_revision)
|
| 161 |
+
)
|
| 162 |
+
rebuild = status in {"missing", "unpublished", "stale", "incomplete"} and not local_current
|
| 163 |
+
publish = status in {"missing", "unpublished", "stale", "incomplete", "stub_vectors"} and (
|
| 164 |
+
"source_missing_laws" not in issues
|
| 165 |
+
)
|
| 166 |
+
return {
|
| 167 |
+
"status": status,
|
| 168 |
+
"issues": issues,
|
| 169 |
+
"rebuild": rebuild,
|
| 170 |
+
"publish": publish,
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def _ir_source_revision(manifest: Mapping[str, Any] | None) -> str | None:
|
| 175 |
+
if not manifest:
|
| 176 |
+
return None
|
| 177 |
+
pinned = manifest.get("dataset_revision") or (manifest.get("source") or {}).get(
|
| 178 |
+
"source_revision"
|
| 179 |
+
)
|
| 180 |
+
text = str(pinned or "").strip()
|
| 181 |
+
return text or None
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def _vector_status(manifest: Mapping[str, Any] | None) -> str | None:
|
| 185 |
+
if not manifest:
|
| 186 |
+
return None
|
| 187 |
+
vector = manifest.get("vector") or {}
|
| 188 |
+
if isinstance(vector, dict) and vector.get("status"):
|
| 189 |
+
return str(vector.get("status"))
|
| 190 |
+
incremental = manifest.get("incremental") or {}
|
| 191 |
+
nested = incremental.get("vectors") if isinstance(incremental, dict) else None
|
| 192 |
+
if isinstance(nested, dict) and nested.get("status"):
|
| 193 |
+
return str(nested.get("status"))
|
| 194 |
+
if isinstance(vector, dict) and vector.get("stub"):
|
| 195 |
+
return "stub"
|
| 196 |
+
return None
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def load_local_manifest(release_dir: Path) -> dict[str, Any]:
|
| 200 |
+
path = Path(release_dir) / "manifest.json"
|
| 201 |
+
if not path.is_file():
|
| 202 |
+
return {}
|
| 203 |
+
try:
|
| 204 |
+
data = json.loads(path.read_text(encoding="utf-8"))
|
| 205 |
+
except Exception:
|
| 206 |
+
return {}
|
| 207 |
+
return data if isinstance(data, dict) else {}
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def _sibling_map(info: Any) -> dict[str, int | None]:
|
| 211 |
+
out: dict[str, int | None] = {}
|
| 212 |
+
for sib in getattr(info, "siblings", None) or []:
|
| 213 |
+
name = str(getattr(sib, "rfilename", "") or "")
|
| 214 |
+
if not name:
|
| 215 |
+
continue
|
| 216 |
+
size = getattr(sib, "size", None)
|
| 217 |
+
try:
|
| 218 |
+
out[name] = int(size) if size is not None else None # type: ignore[assignment]
|
| 219 |
+
except (TypeError, ValueError):
|
| 220 |
+
out[name] = None # type: ignore[assignment]
|
| 221 |
+
return out
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def _inspect_source(slug: str, cache_dir: Path | None = None) -> dict[str, Any]:
|
| 225 |
+
from huggingface_hub import dataset_info
|
| 226 |
+
|
| 227 |
+
from .auth import configure_hf, operator_token, public_token
|
| 228 |
+
|
| 229 |
+
repo = f"endomorphosis/ipfs_{slug}_laws"
|
| 230 |
+
configure_hf()
|
| 231 |
+
info = dataset_info(repo, token=operator_token() or public_token())
|
| 232 |
+
files = _sibling_map(info)
|
| 233 |
+
laws_file = next(
|
| 234 |
+
(name for name in ("data/laws.parquet", "laws.parquet") if name in files),
|
| 235 |
+
None,
|
| 236 |
+
)
|
| 237 |
+
arts_file = next(
|
| 238 |
+
(name for name in ("data/articles.parquet", "articles.parquet") if name in files),
|
| 239 |
+
None,
|
| 240 |
+
)
|
| 241 |
+
return {
|
| 242 |
+
"repo": repo,
|
| 243 |
+
"revision": getattr(info, "sha", None),
|
| 244 |
+
"files": sorted(files),
|
| 245 |
+
"has_laws": laws_file is not None,
|
| 246 |
+
"has_articles": arts_file is not None,
|
| 247 |
+
"laws_bytes": files.get(laws_file) if laws_file else None,
|
| 248 |
+
"articles_bytes": files.get(arts_file) if arts_file else None,
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def _inspect_ir(slug: str, cache_dir: Path) -> dict[str, Any] | None:
|
| 253 |
+
from huggingface_hub import HfApi, dataset_info, hf_hub_download
|
| 254 |
+
from huggingface_hub.errors import EntryNotFoundError, RepositoryNotFoundError
|
| 255 |
+
|
| 256 |
+
from .auth import configure_hf, operator_token, public_token
|
| 257 |
+
|
| 258 |
+
repo = target_repo(slug)
|
| 259 |
+
configure_hf()
|
| 260 |
+
token = operator_token() or public_token()
|
| 261 |
+
try:
|
| 262 |
+
info = dataset_info(repo, token=token)
|
| 263 |
+
except RepositoryNotFoundError:
|
| 264 |
+
return None
|
| 265 |
+
files = _sibling_map(info)
|
| 266 |
+
if len(files) < 8:
|
| 267 |
+
try:
|
| 268 |
+
listed = HfApi(token=token).list_repo_files(repo_id=repo, repo_type="dataset")
|
| 269 |
+
for name in listed:
|
| 270 |
+
files.setdefault(str(name), None)
|
| 271 |
+
except Exception:
|
| 272 |
+
pass
|
| 273 |
+
manifest: dict[str, Any] = {}
|
| 274 |
+
if "manifest.json" in files:
|
| 275 |
+
try:
|
| 276 |
+
path = hf_hub_download(
|
| 277 |
+
repo_id=repo,
|
| 278 |
+
filename="manifest.json",
|
| 279 |
+
repo_type="dataset",
|
| 280 |
+
token=token,
|
| 281 |
+
cache_dir=str(cache_dir / "hf"),
|
| 282 |
+
)
|
| 283 |
+
payload = json.loads(Path(path).read_text(encoding="utf-8"))
|
| 284 |
+
if isinstance(payload, dict):
|
| 285 |
+
manifest = payload
|
| 286 |
+
except (EntryNotFoundError, OSError, json.JSONDecodeError):
|
| 287 |
+
manifest = {}
|
| 288 |
+
counts = manifest.get("counts") if isinstance(manifest.get("counts"), dict) else {}
|
| 289 |
+
return {
|
| 290 |
+
"repo": repo,
|
| 291 |
+
"hub_revision": getattr(info, "sha", None),
|
| 292 |
+
"files": sorted(files),
|
| 293 |
+
"manifest": manifest,
|
| 294 |
+
"source_revision": _ir_source_revision(manifest),
|
| 295 |
+
"corpus_rows": counts.get("corpus_rows"),
|
| 296 |
+
"vector_status": _vector_status(manifest),
|
| 297 |
+
}
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def gap_report(
|
| 301 |
+
releases_dir: Path | None = None,
|
| 302 |
+
*,
|
| 303 |
+
slugs: list[str] | None = None,
|
| 304 |
+
workers: int = 8,
|
| 305 |
+
) -> dict[str, Any]:
|
| 306 |
+
"""Live Hub scan: missing, stale, incomplete, and unpublished country IR."""
|
| 307 |
+
from .build import CACHE, RELEASES
|
| 308 |
+
|
| 309 |
+
sources = slugs or [
|
| 310 |
+
s
|
| 311 |
+
for s in list_hub_slugs(author="endomorphosis", kind="source")
|
| 312 |
+
if s not in ALIAS_TO_CANONICAL
|
| 313 |
+
]
|
| 314 |
+
hub_ir = set(list_hub_slugs(author="justicedao", kind="ir"))
|
| 315 |
+
local_dir = Path(releases_dir) if releases_dir else RELEASES
|
| 316 |
+
local_ir = set(local_release_slugs(local_dir))
|
| 317 |
+
cache_dir = CACHE
|
| 318 |
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
| 319 |
+
|
| 320 |
+
rows: list[dict[str, Any]] = []
|
| 321 |
+
|
| 322 |
+
def _one(slug: str) -> dict[str, Any]:
|
| 323 |
+
last_exc: Exception | None = None
|
| 324 |
+
for attempt in range(4):
|
| 325 |
+
try:
|
| 326 |
+
source = _inspect_source(slug)
|
| 327 |
+
ir = _inspect_ir(slug, cache_dir) if slug in hub_ir else None
|
| 328 |
+
break
|
| 329 |
+
except Exception as exc:
|
| 330 |
+
last_exc = exc
|
| 331 |
+
name = type(exc).__name__
|
| 332 |
+
msg = str(exc)
|
| 333 |
+
if "429" in msg or "rate limit" in msg.lower():
|
| 334 |
+
time.sleep(min(45, 3 ** attempt * 2))
|
| 335 |
+
continue
|
| 336 |
+
raise
|
| 337 |
+
else:
|
| 338 |
+
raise last_exc or RuntimeError(f"scan failed for {slug}")
|
| 339 |
+
local_manifest = load_local_manifest(local_dir / f"ipfs_{slug}_laws_ir")
|
| 340 |
+
local_rev = _ir_source_revision(local_manifest) if local_manifest else None
|
| 341 |
+
classified = classify_gap(
|
| 342 |
+
excluded=slug in EXCLUDED_SLUGS,
|
| 343 |
+
alias=False,
|
| 344 |
+
source_has_laws=bool(source.get("has_laws")),
|
| 345 |
+
source_laws_bytes=source.get("laws_bytes"),
|
| 346 |
+
source_revision=source.get("revision"),
|
| 347 |
+
ir_files=None if ir is None else ir.get("files"),
|
| 348 |
+
ir_source_revision=(ir or {}).get("source_revision") or local_rev,
|
| 349 |
+
ir_corpus_rows=(ir or {}).get("corpus_rows")
|
| 350 |
+
if ir is not None
|
| 351 |
+
else (local_manifest.get("counts") or {}).get("corpus_rows")
|
| 352 |
+
if local_manifest
|
| 353 |
+
else None,
|
| 354 |
+
vector_status=(ir or {}).get("vector_status")
|
| 355 |
+
or _vector_status(local_manifest),
|
| 356 |
+
local_only=slug in local_ir and slug not in hub_ir,
|
| 357 |
+
local_source_revision=local_rev,
|
| 358 |
+
)
|
| 359 |
+
return {
|
| 360 |
+
"slug": slug,
|
| 361 |
+
"source": source.get("repo"),
|
| 362 |
+
"target": target_repo(slug),
|
| 363 |
+
"source_revision": source.get("revision"),
|
| 364 |
+
"ir_source_revision": (ir or {}).get("source_revision"),
|
| 365 |
+
"local_source_revision": local_rev,
|
| 366 |
+
"has_hub_ir": ir is not None,
|
| 367 |
+
"has_local_ir": slug in local_ir,
|
| 368 |
+
"source_has_articles": source.get("has_articles"),
|
| 369 |
+
"source_laws_bytes": source.get("laws_bytes"),
|
| 370 |
+
"corpus_rows": (ir or {}).get("corpus_rows")
|
| 371 |
+
if ir is not None
|
| 372 |
+
else (local_manifest.get("counts") or {}).get("corpus_rows")
|
| 373 |
+
if local_manifest
|
| 374 |
+
else None,
|
| 375 |
+
"vector_status": (ir or {}).get("vector_status")
|
| 376 |
+
or _vector_status(local_manifest),
|
| 377 |
+
**classified,
|
| 378 |
+
}
|
| 379 |
+
|
| 380 |
+
workers = max(1, min(int(workers), 16))
|
| 381 |
+
with ThreadPoolExecutor(max_workers=workers) as pool:
|
| 382 |
+
futs = {pool.submit(_one, slug): slug for slug in sources}
|
| 383 |
+
for fut in as_completed(futs):
|
| 384 |
+
slug = futs[fut]
|
| 385 |
+
try:
|
| 386 |
+
rows.append(fut.result())
|
| 387 |
+
except Exception as exc:
|
| 388 |
+
rows.append(
|
| 389 |
+
{
|
| 390 |
+
"slug": slug,
|
| 391 |
+
"source": f"endomorphosis/ipfs_{slug}_laws",
|
| 392 |
+
"target": target_repo(slug),
|
| 393 |
+
"status": "incomplete",
|
| 394 |
+
"issues": [f"scan_error:{type(exc).__name__}"],
|
| 395 |
+
"rebuild": False,
|
| 396 |
+
"publish": False,
|
| 397 |
+
"error": str(exc),
|
| 398 |
+
}
|
| 399 |
+
)
|
| 400 |
+
rows.sort(key=lambda r: str(r.get("slug")))
|
| 401 |
+
by_status: dict[str, list[str]] = {}
|
| 402 |
+
for row in rows:
|
| 403 |
+
by_status.setdefault(str(row.get("status")), []).append(str(row.get("slug")))
|
| 404 |
+
return {
|
| 405 |
+
"n": len(rows),
|
| 406 |
+
"by_status": {k: sorted(v) for k, v in sorted(by_status.items())},
|
| 407 |
+
"counts": {k: len(v) for k, v in sorted(by_status.items())},
|
| 408 |
+
"rebuild": [r["slug"] for r in rows if r.get("rebuild")],
|
| 409 |
+
"publish": [r["slug"] for r in rows if r.get("publish")],
|
| 410 |
+
"countries": rows,
|
| 411 |
+
}
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
def coverage_report(releases_dir: Path | None = None) -> dict[str, Any]:
|
| 415 |
+
from .build import RELEASES
|
| 416 |
+
|
| 417 |
+
sources = list_hub_slugs(author="endomorphosis", kind="source")
|
| 418 |
+
hub_ir = list_hub_slugs(author="justicedao", kind="ir")
|
| 419 |
+
local_ir = local_release_slugs(Path(releases_dir) if releases_dir else RELEASES)
|
| 420 |
+
hub_ir_canon = {canonical_slug(s) for s in hub_ir}
|
| 421 |
+
local_ir_canon = {canonical_slug(s) for s in local_ir}
|
| 422 |
+
missing_hub: list[dict[str, Any]] = []
|
| 423 |
+
missing_local: list[dict[str, Any]] = []
|
| 424 |
+
excluded: list[str] = []
|
| 425 |
+
aliases: list[str] = []
|
| 426 |
+
for slug in sources:
|
| 427 |
+
if slug in ALIAS_TO_CANONICAL:
|
| 428 |
+
aliases.append(slug)
|
| 429 |
+
continue
|
| 430 |
+
if slug in EXCLUDED_SLUGS:
|
| 431 |
+
excluded.append(slug)
|
| 432 |
+
continue
|
| 433 |
+
row = {
|
| 434 |
+
"slug": slug,
|
| 435 |
+
"source": f"endomorphosis/ipfs_{slug}_laws",
|
| 436 |
+
"target": target_repo(slug),
|
| 437 |
+
}
|
| 438 |
+
if slug not in hub_ir_canon:
|
| 439 |
+
missing_hub.append(row)
|
| 440 |
+
if slug not in local_ir_canon and slug not in hub_ir_canon:
|
| 441 |
+
missing_local.append(row)
|
| 442 |
+
return {
|
| 443 |
+
"n_sources": len(sources),
|
| 444 |
+
"n_hub_ir": len(hub_ir),
|
| 445 |
+
"n_local_ir": len(local_ir),
|
| 446 |
+
"n_catalog": len(all_countries()),
|
| 447 |
+
"excluded": excluded,
|
| 448 |
+
"alias_sources": aliases,
|
| 449 |
+
"missing_justicedao": missing_hub,
|
| 450 |
+
"missing_local_and_hub": missing_local,
|
| 451 |
+
"local_only": sorted(local_ir_canon - hub_ir_canon),
|
| 452 |
+
}
|
country_laws_ir/duckdb_store.py
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""DuckDB views over country-laws sparse GraphRAG parquet shards.
|
| 2 |
+
|
| 3 |
+
Published artifacts are ZSTD parquet (SkillCenter / publicus-ir family).
|
| 4 |
+
Query and large-corpus neighbor generation read those shards through DuckDB
|
| 5 |
+
instead of loading them into pandas or SQLite.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import json
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from typing import Any
|
| 13 |
+
|
| 14 |
+
import pandas as pd
|
| 15 |
+
|
| 16 |
+
K1 = 1.2
|
| 17 |
+
B = 0.75
|
| 18 |
+
TITLE_WEIGHT = 5.0
|
| 19 |
+
BODY_WEIGHT = 1.0
|
| 20 |
+
MAX_QUERY_TERMS = 64
|
| 21 |
+
|
| 22 |
+
VIEWS = (
|
| 23 |
+
("corpus", "data/corpus/*.parquet"),
|
| 24 |
+
("bm25_documents", "data/bm25/documents/*.parquet"),
|
| 25 |
+
("bm25_postings", "data/bm25/postings/*.parquet"),
|
| 26 |
+
("graph_nodes", "data/graph/nodes/*.parquet"),
|
| 27 |
+
("graph_edges", "data/graph/edges/*.parquet"),
|
| 28 |
+
# Shared hf_graphrag layout (US Code / state laws / FR).
|
| 29 |
+
("graph_in", "data/graph/adjacency/in/*.parquet"),
|
| 30 |
+
("graph_out", "data/graph/adjacency/out/*.parquet"),
|
| 31 |
+
# Legacy country-laws-ir layout still on some Hub packs.
|
| 32 |
+
("graph_incoming", "data/graph/adjacency/incoming/*.parquet"),
|
| 33 |
+
("graph_outgoing", "data/graph/adjacency/outgoing/*.parquet"),
|
| 34 |
+
("vectors", "data/vectors/*.parquet"),
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class DuckDBStoreError(RuntimeError):
|
| 39 |
+
"""Raised when a parquet/DuckDB sparse index cannot be opened."""
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _require_duckdb():
|
| 43 |
+
try:
|
| 44 |
+
import duckdb # type: ignore
|
| 45 |
+
except ImportError as exc:
|
| 46 |
+
raise DuckDBStoreError("duckdb is required for parquet sparse GraphRAG query") from exc
|
| 47 |
+
return duckdb
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def parquet_glob(root: Path, pattern: str) -> str:
|
| 51 |
+
return str(Path(root) / pattern)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def connect_release(root: Path, *, database: str = ":memory:"):
|
| 55 |
+
"""Open a DuckDB connection with views over parquet shards."""
|
| 56 |
+
duckdb = _require_duckdb()
|
| 57 |
+
root = Path(root)
|
| 58 |
+
if not (root / "manifest.json").is_file():
|
| 59 |
+
raise DuckDBStoreError(f"release missing manifest.json: {root}")
|
| 60 |
+
con = duckdb.connect(database)
|
| 61 |
+
for name, pattern in VIEWS:
|
| 62 |
+
glob = parquet_glob(root, pattern)
|
| 63 |
+
if list(root.glob(pattern)):
|
| 64 |
+
escaped = glob.replace("'", "''")
|
| 65 |
+
con.execute(
|
| 66 |
+
f"CREATE OR REPLACE VIEW {name} AS SELECT * FROM read_parquet('{escaped}')"
|
| 67 |
+
)
|
| 68 |
+
return con
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def load_manifest(root: Path) -> dict[str, Any]:
|
| 72 |
+
return json.loads((Path(root) / "manifest.json").read_text(encoding="utf-8"))
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def tokenize(text: str) -> list[str]:
|
| 76 |
+
import re
|
| 77 |
+
import unicodedata
|
| 78 |
+
|
| 79 |
+
if not text:
|
| 80 |
+
return []
|
| 81 |
+
nfkd = unicodedata.normalize("NFKD", text)
|
| 82 |
+
folded = "".join(ch for ch in nfkd if not unicodedata.combining(ch)).lower()
|
| 83 |
+
return re.findall(r"[0-9A-Za-z]+", folded)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def bm25_search(root: Path, query: str, top_k: int = 10) -> list[dict[str, Any]]:
|
| 87 |
+
"""Okapi BM25 over parquet posting shards via DuckDB UNNEST."""
|
| 88 |
+
terms = tokenize(query)[:MAX_QUERY_TERMS]
|
| 89 |
+
if not terms:
|
| 90 |
+
return []
|
| 91 |
+
manifest = load_manifest(root)
|
| 92 |
+
avgdl = float((manifest.get("bm25") or {}).get("average_document_length") or 1.0) or 1.0
|
| 93 |
+
con = connect_release(root)
|
| 94 |
+
try:
|
| 95 |
+
tables = {
|
| 96 |
+
r[0]
|
| 97 |
+
for r in con.execute(
|
| 98 |
+
"SELECT table_name FROM information_schema.tables WHERE table_schema = 'main'"
|
| 99 |
+
).fetchall()
|
| 100 |
+
}
|
| 101 |
+
if "bm25_postings" not in tables or "bm25_documents" not in tables:
|
| 102 |
+
raise DuckDBStoreError("release is missing BM25 parquet shards")
|
| 103 |
+
placeholders = ", ".join(["?"] * len(terms))
|
| 104 |
+
sql = f"""
|
| 105 |
+
WITH exploded AS (
|
| 106 |
+
SELECT
|
| 107 |
+
unnest(document_indices) AS document_index,
|
| 108 |
+
unnest(title_frequencies) AS title_tf,
|
| 109 |
+
unnest(body_frequencies) AS body_tf,
|
| 110 |
+
unnest(document_lengths) AS dl,
|
| 111 |
+
idf
|
| 112 |
+
FROM bm25_postings
|
| 113 |
+
WHERE term IN ({placeholders})
|
| 114 |
+
),
|
| 115 |
+
scored AS (
|
| 116 |
+
SELECT
|
| 117 |
+
document_index,
|
| 118 |
+
SUM(
|
| 119 |
+
idf * (
|
| 120 |
+
( {TITLE_WEIGHT} * title_tf + {BODY_WEIGHT} * body_tf )
|
| 121 |
+
* ({K1} + 1.0)
|
| 122 |
+
) / (
|
| 123 |
+
( {TITLE_WEIGHT} * title_tf + {BODY_WEIGHT} * body_tf )
|
| 124 |
+
+ {K1} * (1.0 - {B} + {B} * (dl / {avgdl}))
|
| 125 |
+
)
|
| 126 |
+
) AS score
|
| 127 |
+
FROM exploded
|
| 128 |
+
GROUP BY document_index
|
| 129 |
+
)
|
| 130 |
+
SELECT
|
| 131 |
+
s.document_index,
|
| 132 |
+
s.score,
|
| 133 |
+
d.entry_cid,
|
| 134 |
+
d.title,
|
| 135 |
+
d.record_type
|
| 136 |
+
FROM scored s
|
| 137 |
+
JOIN bm25_documents d USING (document_index)
|
| 138 |
+
ORDER BY s.score DESC, s.document_index
|
| 139 |
+
LIMIT ?
|
| 140 |
+
"""
|
| 141 |
+
rows = con.execute(sql, [*terms, int(top_k)]).fetchall()
|
| 142 |
+
cols = [
|
| 143 |
+
"document_index",
|
| 144 |
+
"score",
|
| 145 |
+
"entry_cid",
|
| 146 |
+
"title",
|
| 147 |
+
"record_type",
|
| 148 |
+
]
|
| 149 |
+
return [dict(zip(cols, row)) for row in rows]
|
| 150 |
+
finally:
|
| 151 |
+
con.close()
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def graph_neighbors(
|
| 155 |
+
root: Path,
|
| 156 |
+
node_cid: str,
|
| 157 |
+
*,
|
| 158 |
+
direction: str = "both",
|
| 159 |
+
limit: int = 25,
|
| 160 |
+
) -> list[dict[str, Any]]:
|
| 161 |
+
"""Adjacency lookup over parquet shards via DuckDB."""
|
| 162 |
+
aliases = {
|
| 163 |
+
"both": ("in", "out", "incoming", "outgoing"),
|
| 164 |
+
"in": ("in", "incoming"),
|
| 165 |
+
"out": ("out", "outgoing"),
|
| 166 |
+
"incoming": ("in", "incoming"),
|
| 167 |
+
"outgoing": ("out", "outgoing"),
|
| 168 |
+
}
|
| 169 |
+
dirs = aliases.get(direction, (direction,))
|
| 170 |
+
con = connect_release(root)
|
| 171 |
+
try:
|
| 172 |
+
tables = {
|
| 173 |
+
r[0]
|
| 174 |
+
for r in con.execute(
|
| 175 |
+
"SELECT table_name FROM information_schema.tables WHERE table_schema = 'main'"
|
| 176 |
+
).fetchall()
|
| 177 |
+
}
|
| 178 |
+
hits: list[dict[str, Any]] = []
|
| 179 |
+
for d in dirs:
|
| 180 |
+
view = {
|
| 181 |
+
"in": "graph_in",
|
| 182 |
+
"out": "graph_out",
|
| 183 |
+
"incoming": "graph_incoming",
|
| 184 |
+
"outgoing": "graph_outgoing",
|
| 185 |
+
}.get(d, d)
|
| 186 |
+
if view not in tables:
|
| 187 |
+
continue
|
| 188 |
+
rows = con.execute(
|
| 189 |
+
f"""
|
| 190 |
+
SELECT node_cid, neighbor_cids, edge_types, scores
|
| 191 |
+
FROM {view}
|
| 192 |
+
WHERE node_cid = ?
|
| 193 |
+
""",
|
| 194 |
+
[node_cid],
|
| 195 |
+
).fetchall()
|
| 196 |
+
for node, neighs, types, scores in rows:
|
| 197 |
+
neighs = list(neighs or [])
|
| 198 |
+
types = list(types or [])
|
| 199 |
+
scores = list(scores or [])
|
| 200 |
+
for i, neigh in enumerate(neighs):
|
| 201 |
+
hits.append(
|
| 202 |
+
{
|
| 203 |
+
"direction": d,
|
| 204 |
+
"node_cid": node,
|
| 205 |
+
"neighbor_cid": neigh,
|
| 206 |
+
"edge_type": types[i] if i < len(types) else "",
|
| 207 |
+
"score": scores[i] if i < len(scores) else None,
|
| 208 |
+
}
|
| 209 |
+
)
|
| 210 |
+
hits.sort(key=lambda r: (-(r["score"] or 0), str(r["neighbor_cid"])))
|
| 211 |
+
return hits[: int(limit)]
|
| 212 |
+
finally:
|
| 213 |
+
con.close()
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def build_fts_index(
|
| 217 |
+
corpus_parquet: Path,
|
| 218 |
+
duckdb_path: Path,
|
| 219 |
+
expected: int,
|
| 220 |
+
*,
|
| 221 |
+
log: Any | None = None,
|
| 222 |
+
) -> Path:
|
| 223 |
+
"""Load corpus parquet into DuckDB and create an FTS index (no SQLite)."""
|
| 224 |
+
duckdb = _require_duckdb()
|
| 225 |
+
duckdb_path = Path(duckdb_path)
|
| 226 |
+
duckdb_path.parent.mkdir(parents=True, exist_ok=True)
|
| 227 |
+
if duckdb_path.exists():
|
| 228 |
+
duckdb_path.unlink()
|
| 229 |
+
escaped = str(Path(corpus_parquet).resolve()).replace("'", "''")
|
| 230 |
+
con = duckdb.connect(str(duckdb_path))
|
| 231 |
+
try:
|
| 232 |
+
con.execute(
|
| 233 |
+
f"""
|
| 234 |
+
CREATE TABLE documents AS
|
| 235 |
+
SELECT
|
| 236 |
+
CAST(document_index AS INTEGER) AS document_index,
|
| 237 |
+
CAST(entry_cid AS VARCHAR) AS entry_cid,
|
| 238 |
+
CAST(COALESCE(title, '') AS VARCHAR) AS title,
|
| 239 |
+
CAST(COALESCE(body, '') AS VARCHAR) AS body
|
| 240 |
+
FROM read_parquet('{escaped}')
|
| 241 |
+
"""
|
| 242 |
+
)
|
| 243 |
+
n = int(con.execute("SELECT COUNT(*) FROM documents").fetchone()[0])
|
| 244 |
+
if n != int(expected):
|
| 245 |
+
raise DuckDBStoreError(f"DuckDB corpus rows {n} != expected {expected}")
|
| 246 |
+
con.execute("INSTALL fts")
|
| 247 |
+
con.execute("LOAD fts")
|
| 248 |
+
con.execute(
|
| 249 |
+
"PRAGMA create_fts_index('documents', 'document_index', 'title', 'body', "
|
| 250 |
+
"stemmer='porter', stopwords='english', ignore='(\\.+)', strip_accents=1, lower=1)"
|
| 251 |
+
)
|
| 252 |
+
if log:
|
| 253 |
+
log(f"duckdb fts ready n={n} path={duckdb_path}")
|
| 254 |
+
finally:
|
| 255 |
+
con.close()
|
| 256 |
+
return duckdb_path
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def stream_neighbors_to_parquet(
|
| 260 |
+
duckdb_path: Path,
|
| 261 |
+
spill: Path,
|
| 262 |
+
n_docs: int,
|
| 263 |
+
*,
|
| 264 |
+
k: int = 8,
|
| 265 |
+
shard: int = 5000,
|
| 266 |
+
batch: int = 256,
|
| 267 |
+
resume: bool = True,
|
| 268 |
+
log: Any | None = None,
|
| 269 |
+
) -> list[Path]:
|
| 270 |
+
"""Stream DuckDB FTS neighbors into flattened neighbor_*.parquet shards."""
|
| 271 |
+
duckdb = _require_duckdb()
|
| 272 |
+
spill = Path(spill)
|
| 273 |
+
spill.mkdir(parents=True, exist_ok=True)
|
| 274 |
+
existing = sorted(spill.glob("neighbors_*.parquet"))
|
| 275 |
+
buf_start = 0
|
| 276 |
+
shard_paths: list[Path] = []
|
| 277 |
+
if resume and existing:
|
| 278 |
+
covered = 0
|
| 279 |
+
for path in existing:
|
| 280 |
+
parts = path.stem.split("_")
|
| 281 |
+
try:
|
| 282 |
+
start_i, end_i = int(parts[1]), int(parts[2])
|
| 283 |
+
except (IndexError, ValueError):
|
| 284 |
+
continue
|
| 285 |
+
if start_i != covered:
|
| 286 |
+
break
|
| 287 |
+
shard_paths.append(path)
|
| 288 |
+
covered = end_i
|
| 289 |
+
buf_start = covered
|
| 290 |
+
if buf_start >= n_docs:
|
| 291 |
+
if log:
|
| 292 |
+
log(f"neighbors resume complete {buf_start}/{n_docs}")
|
| 293 |
+
return shard_paths
|
| 294 |
+
for path in existing:
|
| 295 |
+
if path not in shard_paths:
|
| 296 |
+
path.unlink(missing_ok=True)
|
| 297 |
+
else:
|
| 298 |
+
for path in existing:
|
| 299 |
+
path.unlink(missing_ok=True)
|
| 300 |
+
|
| 301 |
+
con = duckdb.connect(str(duckdb_path), read_only=True)
|
| 302 |
+
con.execute("LOAD fts")
|
| 303 |
+
rows_buf: list[dict[str, Any]] = []
|
| 304 |
+
shard_start = buf_start
|
| 305 |
+
last_idx = buf_start - 1
|
| 306 |
+
done = buf_start
|
| 307 |
+
try:
|
| 308 |
+
while True:
|
| 309 |
+
batch_rows = con.execute(
|
| 310 |
+
"SELECT document_index, title, body FROM documents "
|
| 311 |
+
"WHERE document_index > ? ORDER BY document_index LIMIT ?",
|
| 312 |
+
[last_idx, batch],
|
| 313 |
+
).fetchall()
|
| 314 |
+
if not batch_rows:
|
| 315 |
+
break
|
| 316 |
+
for di, title, body in batch_rows:
|
| 317 |
+
di = int(di)
|
| 318 |
+
query = (str(title or "").strip() or str(body or "")[:800]).strip()
|
| 319 |
+
hits: list[tuple[int, float]] = []
|
| 320 |
+
if query:
|
| 321 |
+
hits = con.execute(
|
| 322 |
+
"SELECT document_index, "
|
| 323 |
+
"fts_main_documents.match_bm25(document_index, ?) AS score "
|
| 324 |
+
"FROM documents "
|
| 325 |
+
"WHERE document_index != ? AND score IS NOT NULL "
|
| 326 |
+
"ORDER BY score DESC, document_index "
|
| 327 |
+
"LIMIT ?",
|
| 328 |
+
[query, di, int(k)],
|
| 329 |
+
).fetchall()
|
| 330 |
+
for neigh_i, score in hits:
|
| 331 |
+
rows_buf.append(
|
| 332 |
+
{
|
| 333 |
+
"source_index": di,
|
| 334 |
+
"neighbor_index": int(neigh_i),
|
| 335 |
+
"score": float(score or 0.0),
|
| 336 |
+
}
|
| 337 |
+
)
|
| 338 |
+
last_idx = di
|
| 339 |
+
done += 1
|
| 340 |
+
if (di + 1 - shard_start) >= shard:
|
| 341 |
+
end = di + 1
|
| 342 |
+
path = spill / f"neighbors_{shard_start:06d}_{end:06d}.parquet"
|
| 343 |
+
pd.DataFrame(rows_buf).to_parquet(path, index=False)
|
| 344 |
+
shard_paths.append(path)
|
| 345 |
+
rows_buf = []
|
| 346 |
+
shard_start = end
|
| 347 |
+
if log:
|
| 348 |
+
log(f"neighbors parquet shard {path.name}")
|
| 349 |
+
if done % 5_000 == 0 and log:
|
| 350 |
+
log(f"duckdb neighbors {done}/{n_docs}")
|
| 351 |
+
if shard_start < n_docs:
|
| 352 |
+
path = spill / f"neighbors_{shard_start:06d}_{n_docs:06d}.parquet"
|
| 353 |
+
pd.DataFrame(rows_buf).to_parquet(path, index=False)
|
| 354 |
+
shard_paths.append(path)
|
| 355 |
+
if log:
|
| 356 |
+
log(f"duckdb neighbors done={done} shards={len(shard_paths)}")
|
| 357 |
+
return shard_paths
|
| 358 |
+
finally:
|
| 359 |
+
con.close()
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def iter_neighbor_parquet_shards(spill: Path) -> Any:
|
| 363 |
+
"""Yield (start_index, list-of-neighbor-lists) from parquet shards."""
|
| 364 |
+
import pandas as pd
|
| 365 |
+
|
| 366 |
+
paths = sorted(Path(spill).glob("neighbors_*.parquet"))
|
| 367 |
+
for path in paths:
|
| 368 |
+
parts = path.stem.split("_")
|
| 369 |
+
start_i = int(parts[1])
|
| 370 |
+
end_i = int(parts[2])
|
| 371 |
+
frame = pd.read_parquet(path)
|
| 372 |
+
part: list[list] = [[] for _ in range(max(0, end_i - start_i))]
|
| 373 |
+
if not frame.empty:
|
| 374 |
+
for rec in frame.itertuples(index=False):
|
| 375 |
+
src = int(rec.source_index)
|
| 376 |
+
offset = src - start_i
|
| 377 |
+
if 0 <= offset < len(part):
|
| 378 |
+
part[offset].append(
|
| 379 |
+
(int(rec.neighbor_index), float(rec.score), [])
|
| 380 |
+
)
|
| 381 |
+
yield start_i, part
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
def materialize_corpus_duckdb(corpus_parquet: Path, duckdb_path: Path) -> Path:
|
| 385 |
+
"""Load a corpus parquet file into a persistent DuckDB database."""
|
| 386 |
+
duckdb = _require_duckdb()
|
| 387 |
+
duckdb_path = Path(duckdb_path)
|
| 388 |
+
duckdb_path.parent.mkdir(parents=True, exist_ok=True)
|
| 389 |
+
if duckdb_path.exists():
|
| 390 |
+
duckdb_path.unlink()
|
| 391 |
+
con = duckdb.connect(str(duckdb_path))
|
| 392 |
+
try:
|
| 393 |
+
con.execute(
|
| 394 |
+
"""
|
| 395 |
+
CREATE TABLE documents AS
|
| 396 |
+
SELECT
|
| 397 |
+
CAST(document_index AS INTEGER) AS document_index,
|
| 398 |
+
CAST(entry_cid AS VARCHAR) AS entry_cid,
|
| 399 |
+
CAST(title AS VARCHAR) AS title,
|
| 400 |
+
CAST(body AS VARCHAR) AS body
|
| 401 |
+
FROM read_parquet(?)
|
| 402 |
+
""",
|
| 403 |
+
[str(corpus_parquet)],
|
| 404 |
+
)
|
| 405 |
+
con.execute("CREATE INDEX documents_idx ON documents(document_index)")
|
| 406 |
+
finally:
|
| 407 |
+
con.close()
|
| 408 |
+
return duckdb_path
|
country_laws_ir/incremental.py
ADDED
|
@@ -0,0 +1,500 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CID-keyed incremental GraphRAG rebuild for country-laws IR.
|
| 2 |
+
|
| 3 |
+
Follows the US Code / patent persistent-index pattern:
|
| 4 |
+
|
| 5 |
+
* ``entry_cid`` is the durable identity (not positional ``document_index``).
|
| 6 |
+
* A matching source revision + parquet digest is a no-op.
|
| 7 |
+
* Unchanged CIDs reuse embeddings; BM25/graph are rebuilt from the current
|
| 8 |
+
corpus because ``document_index`` is a shard pointer, not an identity.
|
| 9 |
+
* Delta refresh is never labeled equivalent to a full rebuild.
|
| 10 |
+
|
| 11 |
+
Public Hub reads stay anonymous. Publication to ``justicedao/*`` is a separate
|
| 12 |
+
gated upload step.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
from dataclasses import dataclass, field
|
| 18 |
+
from enum import Enum
|
| 19 |
+
import json
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
from typing import Any, Iterable, Mapping
|
| 22 |
+
|
| 23 |
+
import pandas as pd
|
| 24 |
+
|
| 25 |
+
from . import SCHEMA_VERSION
|
| 26 |
+
|
| 27 |
+
class RebuildKind(str, Enum):
|
| 28 |
+
UNCHANGED = "unchanged"
|
| 29 |
+
DELTA_REFRESH = "delta_refresh"
|
| 30 |
+
FULL_REBUILD = "full_rebuild"
|
| 31 |
+
|
| 32 |
+
@classmethod
|
| 33 |
+
def coerce(cls, value: Any) -> "RebuildKind":
|
| 34 |
+
if isinstance(value, RebuildKind):
|
| 35 |
+
return value
|
| 36 |
+
text = str(value or "").strip().lower().replace("-", "_")
|
| 37 |
+
aliases = {
|
| 38 |
+
"skip": cls.UNCHANGED,
|
| 39 |
+
"noop": cls.UNCHANGED,
|
| 40 |
+
"none": cls.UNCHANGED,
|
| 41 |
+
"delta": cls.DELTA_REFRESH,
|
| 42 |
+
"incremental": cls.DELTA_REFRESH,
|
| 43 |
+
"partial": cls.DELTA_REFRESH,
|
| 44 |
+
"full": cls.FULL_REBUILD,
|
| 45 |
+
"rebuild": cls.FULL_REBUILD,
|
| 46 |
+
"force": cls.FULL_REBUILD,
|
| 47 |
+
}
|
| 48 |
+
if text in aliases:
|
| 49 |
+
return aliases[text]
|
| 50 |
+
for kind in cls:
|
| 51 |
+
if kind.value == text or kind.name.lower() == text:
|
| 52 |
+
return kind
|
| 53 |
+
raise ValueError(f"unknown rebuild kind: {value!r}")
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class BuildMode(str, Enum):
|
| 57 |
+
AUTO = "auto"
|
| 58 |
+
FULL = "full"
|
| 59 |
+
DELTA = "delta"
|
| 60 |
+
|
| 61 |
+
@classmethod
|
| 62 |
+
def coerce(cls, value: Any) -> "BuildMode":
|
| 63 |
+
if isinstance(value, BuildMode):
|
| 64 |
+
return value
|
| 65 |
+
text = str(value or "").strip().lower().replace("-", "_")
|
| 66 |
+
aliases = {
|
| 67 |
+
"incremental": cls.DELTA,
|
| 68 |
+
"diff": cls.DELTA,
|
| 69 |
+
"rebuild": cls.FULL,
|
| 70 |
+
"complete": cls.FULL,
|
| 71 |
+
}
|
| 72 |
+
if text in aliases:
|
| 73 |
+
return aliases[text]
|
| 74 |
+
for mode in cls:
|
| 75 |
+
if mode.value == text or mode.name.lower() == text:
|
| 76 |
+
return mode
|
| 77 |
+
raise ValueError(f"unknown build mode: {value!r}")
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@dataclass(frozen=True)
|
| 81 |
+
class CorpusDelta:
|
| 82 |
+
added_cids: tuple[str, ...] = ()
|
| 83 |
+
removed_cids: tuple[str, ...] = ()
|
| 84 |
+
unchanged_cids: tuple[str, ...] = ()
|
| 85 |
+
prior_count: int = 0
|
| 86 |
+
current_count: int = 0
|
| 87 |
+
changed_ratio: float = 1.0
|
| 88 |
+
equivalent_to_full: bool = False
|
| 89 |
+
|
| 90 |
+
@property
|
| 91 |
+
def n_added(self) -> int:
|
| 92 |
+
return len(self.added_cids)
|
| 93 |
+
|
| 94 |
+
@property
|
| 95 |
+
def n_removed(self) -> int:
|
| 96 |
+
return len(self.removed_cids)
|
| 97 |
+
|
| 98 |
+
@property
|
| 99 |
+
def n_unchanged(self) -> int:
|
| 100 |
+
return len(self.unchanged_cids)
|
| 101 |
+
|
| 102 |
+
def to_dict(self, *, include_cids: bool = False, cid_sample: int = 8) -> dict[str, Any]:
|
| 103 |
+
payload = {
|
| 104 |
+
"n_added": self.n_added,
|
| 105 |
+
"n_removed": self.n_removed,
|
| 106 |
+
"n_unchanged": self.n_unchanged,
|
| 107 |
+
"prior_count": self.prior_count,
|
| 108 |
+
"current_count": self.current_count,
|
| 109 |
+
"changed_ratio": self.changed_ratio,
|
| 110 |
+
"equivalent_to_full": self.equivalent_to_full,
|
| 111 |
+
}
|
| 112 |
+
if include_cids:
|
| 113 |
+
payload["added_cids"] = list(self.added_cids)
|
| 114 |
+
payload["removed_cids"] = list(self.removed_cids)
|
| 115 |
+
payload["unchanged_cids"] = list(self.unchanged_cids)
|
| 116 |
+
else:
|
| 117 |
+
payload["added_cids_sample"] = list(self.added_cids[:cid_sample])
|
| 118 |
+
payload["removed_cids_sample"] = list(self.removed_cids[:cid_sample])
|
| 119 |
+
return payload
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
@dataclass(frozen=True)
|
| 123 |
+
class RebuildPlan:
|
| 124 |
+
kind: RebuildKind
|
| 125 |
+
mode: BuildMode
|
| 126 |
+
reason: str
|
| 127 |
+
source_revision: str
|
| 128 |
+
prior_revision: str | None = None
|
| 129 |
+
source_fingerprint: str = ""
|
| 130 |
+
prior_fingerprint: str | None = None
|
| 131 |
+
delta: CorpusDelta | None = None
|
| 132 |
+
reuse_embeddings: bool = False
|
| 133 |
+
skip_build: bool = False
|
| 134 |
+
equivalent_to_full: bool = False
|
| 135 |
+
|
| 136 |
+
def to_dict(self) -> dict[str, Any]:
|
| 137 |
+
return {
|
| 138 |
+
"kind": self.kind.value,
|
| 139 |
+
"mode": self.mode.value,
|
| 140 |
+
"reason": self.reason,
|
| 141 |
+
"source_revision": self.source_revision,
|
| 142 |
+
"prior_revision": self.prior_revision,
|
| 143 |
+
"source_fingerprint": self.source_fingerprint,
|
| 144 |
+
"prior_fingerprint": self.prior_fingerprint,
|
| 145 |
+
"delta": None if self.delta is None else self.delta.to_dict(include_cids=False),
|
| 146 |
+
"reuse_embeddings": self.reuse_embeddings,
|
| 147 |
+
"skip_build": self.skip_build,
|
| 148 |
+
"equivalent_to_full": self.equivalent_to_full,
|
| 149 |
+
"schema_version": SCHEMA_VERSION,
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
@dataclass
|
| 154 |
+
class PriorRelease:
|
| 155 |
+
directory: Path
|
| 156 |
+
manifest: dict[str, Any] = field(default_factory=dict)
|
| 157 |
+
corpus: pd.DataFrame | None = None
|
| 158 |
+
vectors_by_cid: dict[str, list[float]] | None = None
|
| 159 |
+
|
| 160 |
+
@property
|
| 161 |
+
def source_revision(self) -> str | None:
|
| 162 |
+
return (
|
| 163 |
+
self.manifest.get("dataset_revision")
|
| 164 |
+
or (self.manifest.get("source") or {}).get("source_revision")
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
@property
|
| 168 |
+
def fingerprint(self) -> str:
|
| 169 |
+
return source_fingerprint_from_manifest(self.manifest)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def source_fingerprint(source_meta: Mapping[str, Any]) -> str:
|
| 173 |
+
"""Stable skip key: Hub SHA plus parquet digests when present."""
|
| 174 |
+
revision = str(source_meta.get("source_revision") or "")
|
| 175 |
+
laws = str(source_meta.get("laws_sha256") or "")
|
| 176 |
+
articles = str(source_meta.get("articles_sha256") or "")
|
| 177 |
+
return f"{revision}|{laws}|{articles}"
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def source_fingerprint_from_manifest(manifest: Mapping[str, Any]) -> str:
|
| 181 |
+
revision = str(
|
| 182 |
+
manifest.get("dataset_revision")
|
| 183 |
+
or (manifest.get("source") or {}).get("source_revision")
|
| 184 |
+
or ""
|
| 185 |
+
)
|
| 186 |
+
sha = manifest.get("input_sha256") or {}
|
| 187 |
+
laws = str(sha.get("laws.parquet") or "")
|
| 188 |
+
articles = str(sha.get("articles.parquet") or "")
|
| 189 |
+
if not laws and not articles:
|
| 190 |
+
src = manifest.get("source") or {}
|
| 191 |
+
laws = str(src.get("laws_sha256") or "")
|
| 192 |
+
articles = str(src.get("articles_sha256") or "")
|
| 193 |
+
return f"{revision}|{laws}|{articles}"
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def _cid_set(frame: pd.DataFrame | None) -> set[str]:
|
| 197 |
+
if frame is None or frame.empty or "entry_cid" not in frame.columns:
|
| 198 |
+
return set()
|
| 199 |
+
return {str(x) for x in frame["entry_cid"].dropna().astype(str) if str(x).strip()}
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def diff_corpus(
|
| 203 |
+
prior: pd.DataFrame | None,
|
| 204 |
+
current: pd.DataFrame,
|
| 205 |
+
) -> CorpusDelta:
|
| 206 |
+
"""Diff two CID-keyed corpora. Same ``entry_cid`` implies same body."""
|
| 207 |
+
current_cids = _cid_set(current)
|
| 208 |
+
prior_cids = _cid_set(prior)
|
| 209 |
+
added = tuple(sorted(current_cids - prior_cids))
|
| 210 |
+
removed = tuple(sorted(prior_cids - current_cids))
|
| 211 |
+
unchanged = tuple(sorted(current_cids & prior_cids))
|
| 212 |
+
current_count = int(len(current_cids))
|
| 213 |
+
prior_count = int(len(prior_cids))
|
| 214 |
+
if current_count == 0:
|
| 215 |
+
ratio = 1.0 if prior_count else 0.0
|
| 216 |
+
else:
|
| 217 |
+
ratio = 1.0 - (len(unchanged) / float(current_count))
|
| 218 |
+
equivalent = prior_count == 0 or (not unchanged and current_count > 0)
|
| 219 |
+
return CorpusDelta(
|
| 220 |
+
added_cids=added,
|
| 221 |
+
removed_cids=removed,
|
| 222 |
+
unchanged_cids=unchanged,
|
| 223 |
+
prior_count=prior_count,
|
| 224 |
+
current_count=current_count,
|
| 225 |
+
changed_ratio=float(ratio),
|
| 226 |
+
equivalent_to_full=equivalent,
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def plan_rebuild(
|
| 231 |
+
*,
|
| 232 |
+
mode: BuildMode | str,
|
| 233 |
+
source_meta: Mapping[str, Any],
|
| 234 |
+
prior: PriorRelease | None,
|
| 235 |
+
current_corpus: pd.DataFrame | None = None,
|
| 236 |
+
force: bool = False,
|
| 237 |
+
) -> RebuildPlan:
|
| 238 |
+
"""Decide skip / delta / full from source fingerprints and CID overlap."""
|
| 239 |
+
mode = BuildMode.coerce(mode)
|
| 240 |
+
revision = str(source_meta.get("source_revision") or "")
|
| 241 |
+
fingerprint = source_fingerprint(source_meta)
|
| 242 |
+
prior_revision = prior.source_revision if prior is not None else None
|
| 243 |
+
prior_fp = prior.fingerprint if prior is not None else None
|
| 244 |
+
|
| 245 |
+
if force or mode is BuildMode.FULL:
|
| 246 |
+
delta = None
|
| 247 |
+
if current_corpus is not None and prior is not None:
|
| 248 |
+
delta = diff_corpus(prior.corpus, current_corpus)
|
| 249 |
+
return RebuildPlan(
|
| 250 |
+
kind=RebuildKind.FULL_REBUILD,
|
| 251 |
+
mode=mode,
|
| 252 |
+
reason="operator forced full rebuild" if force else "build mode is full",
|
| 253 |
+
source_revision=revision,
|
| 254 |
+
prior_revision=prior_revision,
|
| 255 |
+
source_fingerprint=fingerprint,
|
| 256 |
+
prior_fingerprint=prior_fp,
|
| 257 |
+
delta=delta,
|
| 258 |
+
reuse_embeddings=False,
|
| 259 |
+
skip_build=False,
|
| 260 |
+
equivalent_to_full=True,
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
if prior is None:
|
| 264 |
+
return RebuildPlan(
|
| 265 |
+
kind=RebuildKind.FULL_REBUILD,
|
| 266 |
+
mode=mode,
|
| 267 |
+
reason="no prior release",
|
| 268 |
+
source_revision=revision,
|
| 269 |
+
prior_revision=None,
|
| 270 |
+
source_fingerprint=fingerprint,
|
| 271 |
+
prior_fingerprint=None,
|
| 272 |
+
delta=None,
|
| 273 |
+
reuse_embeddings=False,
|
| 274 |
+
skip_build=False,
|
| 275 |
+
equivalent_to_full=True,
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
if prior_fp == fingerprint and fingerprint.strip("|"):
|
| 279 |
+
return RebuildPlan(
|
| 280 |
+
kind=RebuildKind.UNCHANGED,
|
| 281 |
+
mode=mode,
|
| 282 |
+
reason="source revision and parquet digests match prior release",
|
| 283 |
+
source_revision=revision,
|
| 284 |
+
prior_revision=prior_revision,
|
| 285 |
+
source_fingerprint=fingerprint,
|
| 286 |
+
prior_fingerprint=prior_fp,
|
| 287 |
+
delta=CorpusDelta(
|
| 288 |
+
unchanged_cids=tuple(sorted(_cid_set(prior.corpus))),
|
| 289 |
+
prior_count=int(len(_cid_set(prior.corpus))),
|
| 290 |
+
current_count=int(len(_cid_set(prior.corpus))),
|
| 291 |
+
changed_ratio=0.0,
|
| 292 |
+
equivalent_to_full=False,
|
| 293 |
+
),
|
| 294 |
+
reuse_embeddings=True,
|
| 295 |
+
skip_build=True,
|
| 296 |
+
equivalent_to_full=False,
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
delta = None
|
| 300 |
+
if current_corpus is not None:
|
| 301 |
+
delta = diff_corpus(prior.corpus, current_corpus)
|
| 302 |
+
if delta.equivalent_to_full:
|
| 303 |
+
return RebuildPlan(
|
| 304 |
+
kind=RebuildKind.FULL_REBUILD,
|
| 305 |
+
mode=mode,
|
| 306 |
+
reason="CID overlap is empty; delta equals a full rebuild",
|
| 307 |
+
source_revision=revision,
|
| 308 |
+
prior_revision=prior_revision,
|
| 309 |
+
source_fingerprint=fingerprint,
|
| 310 |
+
prior_fingerprint=prior_fp,
|
| 311 |
+
delta=delta,
|
| 312 |
+
reuse_embeddings=False,
|
| 313 |
+
skip_build=False,
|
| 314 |
+
equivalent_to_full=True,
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
return RebuildPlan(
|
| 318 |
+
kind=RebuildKind.DELTA_REFRESH,
|
| 319 |
+
mode=mode,
|
| 320 |
+
reason="source changed; reuse embeddings for unchanged entry_cids",
|
| 321 |
+
source_revision=revision,
|
| 322 |
+
prior_revision=prior_revision,
|
| 323 |
+
source_fingerprint=fingerprint,
|
| 324 |
+
prior_fingerprint=prior_fp,
|
| 325 |
+
delta=delta,
|
| 326 |
+
reuse_embeddings=True,
|
| 327 |
+
skip_build=False,
|
| 328 |
+
equivalent_to_full=False,
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def _read_sharded_parquet(directory: Path) -> pd.DataFrame | None:
|
| 333 |
+
if not directory.is_dir():
|
| 334 |
+
return None
|
| 335 |
+
parts = sorted(directory.glob("part-*.parquet"))
|
| 336 |
+
if not parts:
|
| 337 |
+
parts = sorted(p for p in directory.rglob("*.parquet") if p.is_file())
|
| 338 |
+
if not parts:
|
| 339 |
+
return None
|
| 340 |
+
frames = [pd.read_parquet(p) for p in parts]
|
| 341 |
+
return pd.concat(frames, ignore_index=True) if frames else None
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def load_release_manifest(release_dir: Path) -> dict[str, Any]:
|
| 345 |
+
path = Path(release_dir) / "manifest.json"
|
| 346 |
+
if not path.is_file():
|
| 347 |
+
return {}
|
| 348 |
+
try:
|
| 349 |
+
data = json.loads(path.read_text(encoding="utf-8"))
|
| 350 |
+
except Exception:
|
| 351 |
+
return {}
|
| 352 |
+
return data if isinstance(data, dict) else {}
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def load_release_corpus(release_dir: Path) -> pd.DataFrame | None:
|
| 356 |
+
release_dir = Path(release_dir)
|
| 357 |
+
corpus = _read_sharded_parquet(release_dir / "data" / "corpus")
|
| 358 |
+
if corpus is not None:
|
| 359 |
+
return corpus
|
| 360 |
+
checkpoint = release_dir / "corpus.parquet"
|
| 361 |
+
if checkpoint.is_file():
|
| 362 |
+
return pd.read_parquet(checkpoint)
|
| 363 |
+
return None
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
def embeddings_from_vector_table(frame: pd.DataFrame) -> dict[str, list[float]]:
|
| 367 |
+
out: dict[str, list[float]] = {}
|
| 368 |
+
if frame is None or frame.empty:
|
| 369 |
+
return out
|
| 370 |
+
if "entry_cid" not in frame.columns or "embedding" not in frame.columns:
|
| 371 |
+
return out
|
| 372 |
+
for rec in frame.itertuples(index=False):
|
| 373 |
+
cid = str(getattr(rec, "entry_cid", "") or "")
|
| 374 |
+
emb = getattr(rec, "embedding", None)
|
| 375 |
+
if not cid or emb is None:
|
| 376 |
+
continue
|
| 377 |
+
if isinstance(emb, float) and pd.isna(emb):
|
| 378 |
+
continue
|
| 379 |
+
try:
|
| 380 |
+
values = [float(x) for x in list(emb)]
|
| 381 |
+
except Exception:
|
| 382 |
+
continue
|
| 383 |
+
if not values:
|
| 384 |
+
continue
|
| 385 |
+
out[cid] = values
|
| 386 |
+
return out
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
def load_release_vectors_by_cid(release_dir: Path) -> dict[str, list[float]]:
|
| 390 |
+
frame = _read_sharded_parquet(Path(release_dir) / "data" / "vectors")
|
| 391 |
+
if frame is None:
|
| 392 |
+
return {}
|
| 393 |
+
return embeddings_from_vector_table(frame)
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def load_prior_release(release_dir: Path | None) -> PriorRelease | None:
|
| 397 |
+
if release_dir is None:
|
| 398 |
+
return None
|
| 399 |
+
directory = Path(release_dir)
|
| 400 |
+
if not directory.is_dir():
|
| 401 |
+
return None
|
| 402 |
+
manifest = load_release_manifest(directory)
|
| 403 |
+
if not manifest and not (directory / "data").is_dir():
|
| 404 |
+
return None
|
| 405 |
+
return PriorRelease(
|
| 406 |
+
directory=directory,
|
| 407 |
+
manifest=manifest,
|
| 408 |
+
corpus=load_release_corpus(directory),
|
| 409 |
+
vectors_by_cid=None,
|
| 410 |
+
)
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def load_embedding_cache(path: Path) -> dict[str, list[float]]:
|
| 414 |
+
if not path.is_file():
|
| 415 |
+
return {}
|
| 416 |
+
try:
|
| 417 |
+
frame = pd.read_parquet(path)
|
| 418 |
+
except Exception:
|
| 419 |
+
return {}
|
| 420 |
+
return embeddings_from_vector_table(frame)
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
def save_embedding_cache(
|
| 424 |
+
path: Path,
|
| 425 |
+
by_cid: Mapping[str, Iterable[float]],
|
| 426 |
+
*,
|
| 427 |
+
model_name: str,
|
| 428 |
+
dimension: int,
|
| 429 |
+
) -> None:
|
| 430 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 431 |
+
rows = [
|
| 432 |
+
{
|
| 433 |
+
"entry_cid": cid,
|
| 434 |
+
"embedding": list(vec),
|
| 435 |
+
"model_name": model_name,
|
| 436 |
+
"dimension": int(dimension),
|
| 437 |
+
}
|
| 438 |
+
for cid, vec in sorted(by_cid.items())
|
| 439 |
+
]
|
| 440 |
+
frame = pd.DataFrame(rows)
|
| 441 |
+
tmp = path.with_suffix(path.suffix + ".tmp")
|
| 442 |
+
frame.to_parquet(tmp, index=False)
|
| 443 |
+
tmp.replace(path)
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def merge_embedding_maps(
|
| 447 |
+
*maps: Mapping[str, list[float]] | None,
|
| 448 |
+
) -> dict[str, list[float]]:
|
| 449 |
+
merged: dict[str, list[float]] = {}
|
| 450 |
+
for mapping in maps:
|
| 451 |
+
if not mapping:
|
| 452 |
+
continue
|
| 453 |
+
merged.update(mapping)
|
| 454 |
+
return merged
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
def fetch_hub_prior(
|
| 458 |
+
slug: str,
|
| 459 |
+
dest: Path | None = None,
|
| 460 |
+
*,
|
| 461 |
+
cache_root: Path | None = None,
|
| 462 |
+
) -> Path | None:
|
| 463 |
+
"""Download JusticeDAO corpus+vector shards to use as an incremental parent.
|
| 464 |
+
|
| 465 |
+
Missing Hub IR is not an error: first-time countries return ``None``.
|
| 466 |
+
"""
|
| 467 |
+
from huggingface_hub import snapshot_download
|
| 468 |
+
from huggingface_hub.errors import RepositoryNotFoundError
|
| 469 |
+
|
| 470 |
+
from .auth import operator_token, public_token
|
| 471 |
+
from .catalog import target_repo
|
| 472 |
+
|
| 473 |
+
root = Path(cache_root) if cache_root is not None else (
|
| 474 |
+
Path.home() / ".ipfs_datasets" / "country-laws-ir" / "cache" / "hub-ir"
|
| 475 |
+
)
|
| 476 |
+
dest = Path(dest) if dest is not None else (root / slug)
|
| 477 |
+
dest.mkdir(parents=True, exist_ok=True)
|
| 478 |
+
repo = target_repo(slug)
|
| 479 |
+
try:
|
| 480 |
+
snapshot_download(
|
| 481 |
+
repo_id=repo,
|
| 482 |
+
repo_type="dataset",
|
| 483 |
+
local_dir=str(dest),
|
| 484 |
+
allow_patterns=[
|
| 485 |
+
"manifest.json",
|
| 486 |
+
"data/vectors/**",
|
| 487 |
+
"data/corpus/**",
|
| 488 |
+
"indexes/vector_chunks.parquet",
|
| 489 |
+
],
|
| 490 |
+
token=operator_token() or public_token(),
|
| 491 |
+
)
|
| 492 |
+
except RepositoryNotFoundError:
|
| 493 |
+
return None
|
| 494 |
+
except Exception:
|
| 495 |
+
if not (dest / "manifest.json").is_file():
|
| 496 |
+
return None
|
| 497 |
+
raise
|
| 498 |
+
if not (dest / "manifest.json").is_file():
|
| 499 |
+
return None
|
| 500 |
+
return dest
|
country_laws_ir/normalize.py
CHANGED
|
@@ -19,6 +19,7 @@ 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
|
|
@@ -27,6 +28,21 @@ 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:
|
|
@@ -53,21 +69,34 @@ def _download(repo_id: str, filename: str, cache_dir: Path) -> Path:
|
|
| 53 |
return Path(path)
|
| 54 |
|
| 55 |
|
| 56 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
"""Accept either <root>/data/<name>.parquet or <root>/<name>.parquet."""
|
| 58 |
for cand in (root / "data" / f"{name}.parquet", root / f"{name}.parquet"):
|
| 59 |
if cand.is_file():
|
| 60 |
return cand
|
| 61 |
-
|
|
|
|
|
|
|
| 62 |
|
| 63 |
|
| 64 |
def load_local_source(local_dir: Path) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]:
|
| 65 |
"""Load a local country-laws pack (filtered preprocess layout)."""
|
| 66 |
local_dir = Path(local_dir).resolve()
|
| 67 |
laws_path = _resolve_local_parquet(local_dir, "laws")
|
| 68 |
-
articles_path = _resolve_local_parquet(local_dir, "articles")
|
| 69 |
laws = pd.read_parquet(laws_path)
|
| 70 |
-
articles = pd.read_parquet(articles_path)
|
| 71 |
validate_laws(laws)
|
| 72 |
validate_articles(articles)
|
| 73 |
pack_meta: dict[str, Any] = {}
|
|
@@ -91,9 +120,9 @@ def load_local_source(local_dir: Path) -> tuple[pd.DataFrame, pd.DataFrame, dict
|
|
| 91 |
"source_dataset": source_dataset,
|
| 92 |
"source_revision": source_revision,
|
| 93 |
"laws_path": str(laws_path),
|
| 94 |
-
"articles_path": str(articles_path),
|
| 95 |
"laws_sha256": sha256_file(laws_path),
|
| 96 |
-
"articles_sha256": sha256_file(articles_path),
|
| 97 |
"n_laws_source": int(len(laws)),
|
| 98 |
"n_articles_source": int(len(articles)),
|
| 99 |
"laws_columns": list(map(str, laws.columns)),
|
|
@@ -118,19 +147,27 @@ def load_source(repo_id: str, cache_dir: Path) -> tuple[pd.DataFrame, pd.DataFra
|
|
| 118 |
os.environ.setdefault("HF_HOME", str(cache_dir / "hf"))
|
| 119 |
info = dataset_info(repo_id, token=public_token())
|
| 120 |
revision = info.sha
|
| 121 |
-
|
| 122 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
laws = pd.read_parquet(laws_path)
|
| 124 |
-
articles = pd.read_parquet(articles_path)
|
| 125 |
validate_laws(laws)
|
| 126 |
validate_articles(articles)
|
| 127 |
meta = {
|
| 128 |
"source_dataset": repo_id,
|
| 129 |
"source_revision": revision,
|
| 130 |
"laws_path": str(laws_path),
|
| 131 |
-
"articles_path": str(articles_path),
|
| 132 |
"laws_sha256": sha256_file(laws_path),
|
| 133 |
-
"articles_sha256": sha256_file(articles_path),
|
| 134 |
"n_laws_source": int(len(laws)),
|
| 135 |
"n_articles_source": int(len(articles)),
|
| 136 |
"laws_columns": list(map(str, laws.columns)),
|
|
|
|
| 19 |
|
| 20 |
import pandas as pd
|
| 21 |
from huggingface_hub import dataset_info, hf_hub_download
|
| 22 |
+
from huggingface_hub.errors import EntryNotFoundError
|
| 23 |
|
| 24 |
from . import ENTRY_IDENTITY_SCHEMA, LAW_IDENTITY_SCHEMA, SCHEMA_VERSION
|
| 25 |
from .auth import configure_hf, public_token
|
|
|
|
| 28 |
|
| 29 |
_WS_RE = re.compile(r"\s+", re.UNICODE)
|
| 30 |
COLLECTOR_DEFAULT = "endomorphosis/ipfs_datasets_py"
|
| 31 |
+
EMPTY_ARTICLE_COLUMNS = (
|
| 32 |
+
"law_id",
|
| 33 |
+
"id",
|
| 34 |
+
"title",
|
| 35 |
+
"text",
|
| 36 |
+
"source_url",
|
| 37 |
+
"document_number",
|
| 38 |
+
"article_number",
|
| 39 |
+
"record_type",
|
| 40 |
+
"metadata_json",
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _empty_articles() -> pd.DataFrame:
|
| 45 |
+
return pd.DataFrame(columns=list(EMPTY_ARTICLE_COLUMNS))
|
| 46 |
|
| 47 |
|
| 48 |
def normalize_text(value: Any) -> str:
|
|
|
|
| 69 |
return Path(path)
|
| 70 |
|
| 71 |
|
| 72 |
+
def _repo_filenames(info: Any) -> set[str]:
|
| 73 |
+
return {str(getattr(s, "rfilename", "") or "") for s in (getattr(info, "siblings", None) or [])}
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _pick_repo_file(filenames: set[str], name: str) -> str | None:
|
| 77 |
+
for cand in (f"data/{name}.parquet", f"{name}.parquet"):
|
| 78 |
+
if cand in filenames:
|
| 79 |
+
return cand
|
| 80 |
+
return None
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _resolve_local_parquet(root: Path, name: str, *, required: bool = True) -> Path | None:
|
| 84 |
"""Accept either <root>/data/<name>.parquet or <root>/<name>.parquet."""
|
| 85 |
for cand in (root / "data" / f"{name}.parquet", root / f"{name}.parquet"):
|
| 86 |
if cand.is_file():
|
| 87 |
return cand
|
| 88 |
+
if required:
|
| 89 |
+
raise FileNotFoundError(f"missing {name}.parquet under {root} (tried data/ and root)")
|
| 90 |
+
return None
|
| 91 |
|
| 92 |
|
| 93 |
def load_local_source(local_dir: Path) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]:
|
| 94 |
"""Load a local country-laws pack (filtered preprocess layout)."""
|
| 95 |
local_dir = Path(local_dir).resolve()
|
| 96 |
laws_path = _resolve_local_parquet(local_dir, "laws")
|
| 97 |
+
articles_path = _resolve_local_parquet(local_dir, "articles", required=False)
|
| 98 |
laws = pd.read_parquet(laws_path)
|
| 99 |
+
articles = pd.read_parquet(articles_path) if articles_path is not None else _empty_articles()
|
| 100 |
validate_laws(laws)
|
| 101 |
validate_articles(articles)
|
| 102 |
pack_meta: dict[str, Any] = {}
|
|
|
|
| 120 |
"source_dataset": source_dataset,
|
| 121 |
"source_revision": source_revision,
|
| 122 |
"laws_path": str(laws_path),
|
| 123 |
+
"articles_path": str(articles_path) if articles_path is not None else None,
|
| 124 |
"laws_sha256": sha256_file(laws_path),
|
| 125 |
+
"articles_sha256": sha256_file(articles_path) if articles_path is not None else None,
|
| 126 |
"n_laws_source": int(len(laws)),
|
| 127 |
"n_articles_source": int(len(articles)),
|
| 128 |
"laws_columns": list(map(str, laws.columns)),
|
|
|
|
| 147 |
os.environ.setdefault("HF_HOME", str(cache_dir / "hf"))
|
| 148 |
info = dataset_info(repo_id, token=public_token())
|
| 149 |
revision = info.sha
|
| 150 |
+
filenames = _repo_filenames(info)
|
| 151 |
+
laws_file = _pick_repo_file(filenames, "laws") or "data/laws.parquet"
|
| 152 |
+
articles_file = _pick_repo_file(filenames, "articles")
|
| 153 |
+
laws_path = _download(repo_id, laws_file, cache_dir)
|
| 154 |
+
articles_path: Path | None = None
|
| 155 |
+
if articles_file is not None:
|
| 156 |
+
try:
|
| 157 |
+
articles_path = _download(repo_id, articles_file, cache_dir)
|
| 158 |
+
except EntryNotFoundError:
|
| 159 |
+
articles_path = None
|
| 160 |
laws = pd.read_parquet(laws_path)
|
| 161 |
+
articles = pd.read_parquet(articles_path) if articles_path is not None else _empty_articles()
|
| 162 |
validate_laws(laws)
|
| 163 |
validate_articles(articles)
|
| 164 |
meta = {
|
| 165 |
"source_dataset": repo_id,
|
| 166 |
"source_revision": revision,
|
| 167 |
"laws_path": str(laws_path),
|
| 168 |
+
"articles_path": str(articles_path) if articles_path is not None else None,
|
| 169 |
"laws_sha256": sha256_file(laws_path),
|
| 170 |
+
"articles_sha256": sha256_file(articles_path) if articles_path is not None else None,
|
| 171 |
"n_laws_source": int(len(laws)),
|
| 172 |
"n_articles_source": int(len(articles)),
|
| 173 |
"laws_columns": list(map(str, laws.columns)),
|
country_laws_ir/package.py
CHANGED
|
@@ -34,8 +34,11 @@ def package_release(
|
|
| 34 |
country: dict[str, Any],
|
| 35 |
code_root: Path,
|
| 36 |
normalization_report: dict[str, Any] | None = None,
|
|
|
|
|
|
|
|
|
|
| 37 |
) -> dict[str, Any]:
|
| 38 |
-
if out.exists():
|
| 39 |
shutil.rmtree(out)
|
| 40 |
out.mkdir(parents=True, exist_ok=True)
|
| 41 |
indexes_dir = out / "indexes"
|
|
@@ -51,78 +54,95 @@ def package_release(
|
|
| 51 |
)
|
| 52 |
write_parquet(indexes_dir / "corpus_chunks.parquet", _index_df(corpus_idx))
|
| 53 |
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
)
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
)
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
vectors_df = vectors["vectors"]
|
| 128 |
# Drop null embeddings for stub releases so parquet stays typed; keep rows when present.
|
|
@@ -195,8 +215,8 @@ def package_release(
|
|
| 195 |
"bm25_documents": int(len(bm25["documents"])),
|
| 196 |
"bm25_keyword_shards": len(posting_idx),
|
| 197 |
"bm25_posting_rows": int(len(postings)),
|
| 198 |
-
"bm25_postings": int(bm25
|
| 199 |
-
"bm25_terms": int(bm25
|
| 200 |
"corpus_chunks": len(corpus_idx),
|
| 201 |
"corpus_rows": int(len(corpus)),
|
| 202 |
"graph_edge_chunks": len(edge_idx),
|
|
@@ -214,9 +234,22 @@ def package_release(
|
|
| 214 |
"n_laws": n_laws,
|
| 215 |
"n_articles": n_articles,
|
| 216 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
|
| 218 |
def idx_desc(name: str) -> dict[str, Any]:
|
| 219 |
path = indexes_dir / name
|
|
|
|
|
|
|
| 220 |
return file_descriptor(path, f"indexes/{name}")
|
| 221 |
|
| 222 |
hub_id = target_repo(country["slug"])
|
|
@@ -247,6 +280,7 @@ def package_release(
|
|
| 247 |
"compression_level": 6,
|
| 248 |
"max_rows_per_file": MAX_ROWS_PER_FILE,
|
| 249 |
"row_group_size": MAX_ROWS_PER_FILE,
|
|
|
|
| 250 |
},
|
| 251 |
"graph": {
|
| 252 |
"adjacency_pointers_per_row": ADJ_POINTERS_PER_ROW,
|
|
@@ -324,12 +358,35 @@ def package_release(
|
|
| 324 |
},
|
| 325 |
"source": source_meta,
|
| 326 |
}
|
|
|
|
|
|
|
| 327 |
(out / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
| 328 |
_write_readme(out, country, source_meta, counts, bm25["stats"], graph["stats"], vectors["stats"], hub_id)
|
| 329 |
_write_gitattributes(out)
|
|
|
|
| 330 |
return manifest
|
| 331 |
|
| 332 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 333 |
def _write_gitattributes(out: Path) -> None:
|
| 334 |
(out / ".gitattributes").write_text(
|
| 335 |
"*.parquet filter=lfs diff=lfs merge=lfs -text\n"
|
|
@@ -546,6 +603,7 @@ def package_release_sequential(
|
|
| 546 |
code_root: Path,
|
| 547 |
normalization_report: dict[str, Any] | None = None,
|
| 548 |
expected_rows: int | None = None,
|
|
|
|
| 549 |
) -> dict[str, Any]:
|
| 550 |
"""Write release layout one section at a time (never hold corpus+bm25+graph+vectors).
|
| 551 |
|
|
@@ -753,6 +811,8 @@ def package_release_sequential(
|
|
| 753 |
|
| 754 |
def idx_desc(name: str) -> dict[str, Any]:
|
| 755 |
path = indexes_dir / name
|
|
|
|
|
|
|
| 756 |
return file_descriptor(path, f"indexes/{name}")
|
| 757 |
|
| 758 |
manifest = {
|
|
@@ -835,11 +895,14 @@ def package_release_sequential(
|
|
| 835 |
},
|
| 836 |
"source": source_meta,
|
| 837 |
}
|
|
|
|
|
|
|
| 838 |
(out / "manifest.json").write_text(
|
| 839 |
json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
|
| 840 |
)
|
| 841 |
_write_readme(out, country, source_meta, counts, bm25_stats, gstats, vstats, hub_id)
|
| 842 |
_write_gitattributes(out)
|
|
|
|
| 843 |
checkpoint("package_seq_done")
|
| 844 |
return manifest
|
| 845 |
|
|
@@ -853,14 +916,20 @@ def package_from_spill(
|
|
| 853 |
code_root: Path,
|
| 854 |
normalization_report: dict[str, Any] | None = None,
|
| 855 |
expected_rows: int | None = None,
|
|
|
|
| 856 |
) -> dict[str, Any]:
|
| 857 |
-
"""Package from spill dir artifacts: bm25_*.parquet, bm25_stats.
|
|
|
|
| 858 |
import pickle as _pickle
|
| 859 |
|
| 860 |
spill = Path(spill)
|
| 861 |
-
|
| 862 |
-
|
| 863 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 864 |
return package_release_sequential(
|
| 865 |
out,
|
| 866 |
corpus_path=Path(corpus_path),
|
|
@@ -874,4 +943,5 @@ def package_from_spill(
|
|
| 874 |
code_root=Path(code_root),
|
| 875 |
normalization_report=normalization_report,
|
| 876 |
expected_rows=expected_rows,
|
|
|
|
| 877 |
)
|
|
|
|
| 34 |
country: dict[str, Any],
|
| 35 |
code_root: Path,
|
| 36 |
normalization_report: dict[str, Any] | None = None,
|
| 37 |
+
extra_manifest: dict[str, Any] | None = None,
|
| 38 |
+
wipe: bool = True,
|
| 39 |
+
skip_bm25_graph: bool = False,
|
| 40 |
) -> dict[str, Any]:
|
| 41 |
+
if wipe and out.exists():
|
| 42 |
shutil.rmtree(out)
|
| 43 |
out.mkdir(parents=True, exist_ok=True)
|
| 44 |
indexes_dir = out / "indexes"
|
|
|
|
| 54 |
)
|
| 55 |
write_parquet(indexes_dir / "corpus_chunks.parquet", _index_df(corpus_idx))
|
| 56 |
|
| 57 |
+
if skip_bm25_graph:
|
| 58 |
+
bm25_doc_idx = []
|
| 59 |
+
posting_idx = []
|
| 60 |
+
postings = pd.DataFrame()
|
| 61 |
+
node_idx = []
|
| 62 |
+
edge_idx = []
|
| 63 |
+
in_idx = []
|
| 64 |
+
out_idx = []
|
| 65 |
+
incoming = pd.DataFrame()
|
| 66 |
+
outgoing = pd.DataFrame()
|
| 67 |
+
bm25 = bm25 or {"documents": pd.DataFrame(), "postings": pd.DataFrame(), "stats": {}}
|
| 68 |
+
graph = graph or {"nodes": pd.DataFrame(), "edges": pd.DataFrame(), "stats": {}}
|
| 69 |
+
else:
|
| 70 |
+
bm25_doc_idx = write_sharded(
|
| 71 |
+
bm25["documents"],
|
| 72 |
+
out / "data" / "bm25" / "documents",
|
| 73 |
+
"data/bm25/documents",
|
| 74 |
+
kind="bm25_documents",
|
| 75 |
+
key_col="entry_cid",
|
| 76 |
+
index_col="document_index",
|
| 77 |
+
)
|
| 78 |
+
write_parquet(indexes_dir / "bm25_document_chunks.parquet", _index_df(bm25_doc_idx))
|
| 79 |
+
|
| 80 |
+
postings = bm25["postings"]
|
| 81 |
+
posting_idx = write_sharded(
|
| 82 |
+
postings,
|
| 83 |
+
out / "data" / "bm25" / "postings",
|
| 84 |
+
"data/bm25/postings",
|
| 85 |
+
kind="bm25_postings",
|
| 86 |
+
key_col="term",
|
| 87 |
+
)
|
| 88 |
+
for row, part_start in zip(posting_idx, range(len(posting_idx))):
|
| 89 |
+
shard_df = postings.iloc[
|
| 90 |
+
part_start * MAX_ROWS_PER_FILE : (part_start + 1) * MAX_ROWS_PER_FILE
|
| 91 |
+
]
|
| 92 |
+
row["term_count"] = int(shard_df["term"].nunique()) if not shard_df.empty else 0
|
| 93 |
+
row["posting_count"] = (
|
| 94 |
+
int(shard_df["document_indices"].map(len).sum()) if not shard_df.empty else 0
|
| 95 |
+
)
|
| 96 |
+
row["token_instance_count"] = row["posting_count"]
|
| 97 |
+
write_parquet(indexes_dir / "bm25_keyword_shards.parquet", _index_df(posting_idx))
|
| 98 |
+
|
| 99 |
+
node_idx = write_sharded(
|
| 100 |
+
graph["nodes"],
|
| 101 |
+
out / "data" / "graph" / "nodes",
|
| 102 |
+
"data/graph/nodes",
|
| 103 |
+
kind="graph_nodes",
|
| 104 |
+
key_col="node_cid",
|
| 105 |
+
)
|
| 106 |
+
write_parquet(indexes_dir / "graph_node_chunks.parquet", _index_df(node_idx))
|
| 107 |
+
|
| 108 |
+
edge_idx = write_sharded(
|
| 109 |
+
graph["edges"],
|
| 110 |
+
out / "data" / "graph" / "edges",
|
| 111 |
+
"data/graph/edges",
|
| 112 |
+
kind="graph_edges",
|
| 113 |
+
key_col="edge_cid",
|
| 114 |
+
)
|
| 115 |
+
write_parquet(indexes_dir / "graph_edge_chunks.parquet", _index_df(edge_idx))
|
| 116 |
+
|
| 117 |
+
incoming = graph["incoming"]
|
| 118 |
+
outgoing = graph["outgoing"]
|
| 119 |
+
in_idx = write_sharded(
|
| 120 |
+
incoming
|
| 121 |
+
if incoming is not None and not incoming.empty
|
| 122 |
+
else pd.DataFrame(columns=["node_cid", "page_index", "direction"]),
|
| 123 |
+
out / "data" / "graph" / "adjacency" / "incoming",
|
| 124 |
+
"data/graph/adjacency/incoming",
|
| 125 |
+
kind="graph_incoming_adjacency",
|
| 126 |
+
key_col="node_cid",
|
| 127 |
+
)
|
| 128 |
+
out_idx = write_sharded(
|
| 129 |
+
outgoing
|
| 130 |
+
if outgoing is not None and not outgoing.empty
|
| 131 |
+
else pd.DataFrame(columns=["node_cid", "page_index", "direction"]),
|
| 132 |
+
out / "data" / "graph" / "adjacency" / "outgoing",
|
| 133 |
+
"data/graph/adjacency/outgoing",
|
| 134 |
+
kind="graph_outgoing_adjacency",
|
| 135 |
+
key_col="node_cid",
|
| 136 |
+
)
|
| 137 |
+
for rows, direction in ((in_idx, "incoming"), (out_idx, "outgoing")):
|
| 138 |
+
for r in rows:
|
| 139 |
+
r["direction"] = direction
|
| 140 |
+
r["adjacency_count"] = r.get("row_count", 0)
|
| 141 |
+
r["node_count"] = r.get("row_count", 0)
|
| 142 |
+
r["first_page_index"] = 0
|
| 143 |
+
r["last_page_index"] = 0
|
| 144 |
+
write_parquet(indexes_dir / "graph_incoming_adjacency.parquet", _index_df(in_idx))
|
| 145 |
+
write_parquet(indexes_dir / "graph_outgoing_adjacency.parquet", _index_df(out_idx))
|
| 146 |
|
| 147 |
vectors_df = vectors["vectors"]
|
| 148 |
# Drop null embeddings for stub releases so parquet stays typed; keep rows when present.
|
|
|
|
| 215 |
"bm25_documents": int(len(bm25["documents"])),
|
| 216 |
"bm25_keyword_shards": len(posting_idx),
|
| 217 |
"bm25_posting_rows": int(len(postings)),
|
| 218 |
+
"bm25_postings": int((bm25.get("stats") or {}).get("n_postings") or 0),
|
| 219 |
+
"bm25_terms": int((bm25.get("stats") or {}).get("n_terms") or 0),
|
| 220 |
"corpus_chunks": len(corpus_idx),
|
| 221 |
"corpus_rows": int(len(corpus)),
|
| 222 |
"graph_edge_chunks": len(edge_idx),
|
|
|
|
| 234 |
"n_laws": n_laws,
|
| 235 |
"n_articles": n_articles,
|
| 236 |
}
|
| 237 |
+
if skip_bm25_graph and extra_manifest and extra_manifest.get("sparse"):
|
| 238 |
+
sparse = extra_manifest["sparse"]
|
| 239 |
+
bm25_counts = (sparse.get("bm25") or {}).get("counts") or {}
|
| 240 |
+
graph_counts = sparse.get("graph") or {}
|
| 241 |
+
counts.update(
|
| 242 |
+
{k: int(v) for k, v in bm25_counts.items() if isinstance(v, (int, float))}
|
| 243 |
+
)
|
| 244 |
+
if graph_counts.get("node_count") is not None:
|
| 245 |
+
counts["graph_nodes"] = int(graph_counts["node_count"])
|
| 246 |
+
if graph_counts.get("edge_count") is not None:
|
| 247 |
+
counts["graph_edges"] = int(graph_counts["edge_count"])
|
| 248 |
|
| 249 |
def idx_desc(name: str) -> dict[str, Any]:
|
| 250 |
path = indexes_dir / name
|
| 251 |
+
if not path.is_file():
|
| 252 |
+
return {"relative_path": f"indexes/{name}", "present": False}
|
| 253 |
return file_descriptor(path, f"indexes/{name}")
|
| 254 |
|
| 255 |
hub_id = target_repo(country["slug"])
|
|
|
|
| 280 |
"compression_level": 6,
|
| 281 |
"max_rows_per_file": MAX_ROWS_PER_FILE,
|
| 282 |
"row_group_size": MAX_ROWS_PER_FILE,
|
| 283 |
+
"query_engine": "duckdb",
|
| 284 |
},
|
| 285 |
"graph": {
|
| 286 |
"adjacency_pointers_per_row": ADJ_POINTERS_PER_ROW,
|
|
|
|
| 358 |
},
|
| 359 |
"source": source_meta,
|
| 360 |
}
|
| 361 |
+
if extra_manifest:
|
| 362 |
+
manifest.update(extra_manifest)
|
| 363 |
(out / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
| 364 |
_write_readme(out, country, source_meta, counts, bm25["stats"], graph["stats"], vectors["stats"], hub_id)
|
| 365 |
_write_gitattributes(out)
|
| 366 |
+
_write_dataset_configs(out)
|
| 367 |
return manifest
|
| 368 |
|
| 369 |
|
| 370 |
+
def _write_dataset_configs(out: Path) -> None:
|
| 371 |
+
configs = {
|
| 372 |
+
"country-laws-ir-graphrag/v1": {
|
| 373 |
+
"data_files": {
|
| 374 |
+
"corpus": "data/corpus/*.parquet",
|
| 375 |
+
"bm25_documents": "data/bm25/documents/*.parquet",
|
| 376 |
+
"bm25_postings": "data/bm25/postings/*.parquet",
|
| 377 |
+
"graph_nodes": "data/graph/nodes/*.parquet",
|
| 378 |
+
"graph_edges": "data/graph/edges/*.parquet",
|
| 379 |
+
"graph_adjacency_out": "data/graph/adjacency/out/*.parquet",
|
| 380 |
+
"graph_adjacency_in": "data/graph/adjacency/in/*.parquet",
|
| 381 |
+
"vectors": "data/vectors/*.parquet",
|
| 382 |
+
}
|
| 383 |
+
}
|
| 384 |
+
}
|
| 385 |
+
(out / "dataset_configs.json").write_text(
|
| 386 |
+
json.dumps(configs, indent=2) + "\n", encoding="utf-8"
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
|
| 390 |
def _write_gitattributes(out: Path) -> None:
|
| 391 |
(out / ".gitattributes").write_text(
|
| 392 |
"*.parquet filter=lfs diff=lfs merge=lfs -text\n"
|
|
|
|
| 603 |
code_root: Path,
|
| 604 |
normalization_report: dict[str, Any] | None = None,
|
| 605 |
expected_rows: int | None = None,
|
| 606 |
+
extra_manifest: dict[str, Any] | None = None,
|
| 607 |
) -> dict[str, Any]:
|
| 608 |
"""Write release layout one section at a time (never hold corpus+bm25+graph+vectors).
|
| 609 |
|
|
|
|
| 811 |
|
| 812 |
def idx_desc(name: str) -> dict[str, Any]:
|
| 813 |
path = indexes_dir / name
|
| 814 |
+
if not path.is_file():
|
| 815 |
+
return {"relative_path": f"indexes/{name}", "present": False}
|
| 816 |
return file_descriptor(path, f"indexes/{name}")
|
| 817 |
|
| 818 |
manifest = {
|
|
|
|
| 895 |
},
|
| 896 |
"source": source_meta,
|
| 897 |
}
|
| 898 |
+
if extra_manifest:
|
| 899 |
+
manifest.update(extra_manifest)
|
| 900 |
(out / "manifest.json").write_text(
|
| 901 |
json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
|
| 902 |
)
|
| 903 |
_write_readme(out, country, source_meta, counts, bm25_stats, gstats, vstats, hub_id)
|
| 904 |
_write_gitattributes(out)
|
| 905 |
+
_write_dataset_configs(out)
|
| 906 |
checkpoint("package_seq_done")
|
| 907 |
return manifest
|
| 908 |
|
|
|
|
| 916 |
code_root: Path,
|
| 917 |
normalization_report: dict[str, Any] | None = None,
|
| 918 |
expected_rows: int | None = None,
|
| 919 |
+
extra_manifest: dict[str, Any] | None = None,
|
| 920 |
) -> dict[str, Any]:
|
| 921 |
+
"""Package from spill dir artifacts: bm25_*.parquet, bm25_stats.json, graph.pkl, vectors.pkl."""
|
| 922 |
+
import json as _json
|
| 923 |
import pickle as _pickle
|
| 924 |
|
| 925 |
spill = Path(spill)
|
| 926 |
+
stats_json = spill / "bm25_stats.json"
|
| 927 |
+
stats_pkl = spill / "bm25_stats.pkl"
|
| 928 |
+
if stats_json.is_file():
|
| 929 |
+
bm25_stats = _json.loads(stats_json.read_text(encoding="utf-8"))
|
| 930 |
+
else:
|
| 931 |
+
with stats_pkl.open("rb") as f:
|
| 932 |
+
bm25_stats = _pickle.load(f)
|
| 933 |
return package_release_sequential(
|
| 934 |
out,
|
| 935 |
corpus_path=Path(corpus_path),
|
|
|
|
| 943 |
code_root=Path(code_root),
|
| 944 |
normalization_report=normalization_report,
|
| 945 |
expected_rows=expected_rows,
|
| 946 |
+
extra_manifest=extra_manifest,
|
| 947 |
)
|
country_laws_ir/query.py
CHANGED
|
@@ -42,6 +42,12 @@ class Release:
|
|
| 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 []
|
|
@@ -124,6 +130,12 @@ class Release:
|
|
| 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:
|
|
@@ -170,7 +182,11 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 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(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
p_n.add_argument("--limit", type=int, default=25)
|
| 175 |
|
| 176 |
args = ap.parse_args(argv)
|
|
|
|
| 42 |
return pd.read_parquet(path)
|
| 43 |
|
| 44 |
def bm25(self, query: str, top_k: int = 10) -> list[dict]:
|
| 45 |
+
try:
|
| 46 |
+
from .duckdb_store import bm25_search
|
| 47 |
+
|
| 48 |
+
return bm25_search(self.root, query, top_k=top_k)
|
| 49 |
+
except Exception:
|
| 50 |
+
pass
|
| 51 |
q_terms = tokenize(query)[:MAX_QUERY_TERMS]
|
| 52 |
if not q_terms:
|
| 53 |
return []
|
|
|
|
| 130 |
return out
|
| 131 |
|
| 132 |
def neighbors(self, node_cid: str, direction: str = "both", limit: int = 25) -> list[dict]:
|
| 133 |
+
try:
|
| 134 |
+
from .duckdb_store import graph_neighbors
|
| 135 |
+
|
| 136 |
+
return graph_neighbors(self.root, node_cid, direction=direction, limit=limit)
|
| 137 |
+
except Exception:
|
| 138 |
+
pass
|
| 139 |
dirs = ["incoming", "outgoing"] if direction == "both" else [direction]
|
| 140 |
hits = []
|
| 141 |
for d in dirs:
|
|
|
|
| 182 |
g_sub = p_g.add_subparsers(dest="graph_cmd", required=True)
|
| 183 |
p_n = g_sub.add_parser("neighbors")
|
| 184 |
p_n.add_argument("node_cid")
|
| 185 |
+
p_n.add_argument(
|
| 186 |
+
"--direction",
|
| 187 |
+
default="both",
|
| 188 |
+
choices=["both", "in", "out", "incoming", "outgoing"],
|
| 189 |
+
)
|
| 190 |
p_n.add_argument("--limit", type=int, default=25)
|
| 191 |
|
| 192 |
args = ap.parse_args(argv)
|
country_laws_ir/raw_package.py
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Incrementally package raw collector instruments into laws/articles parquet.
|
| 2 |
+
|
| 3 |
+
Collectors write one JSON instrument per official page under
|
| 4 |
+
``$LEGAL_CORPORA_ROOT/<iso>/instruments/*.json``. Those files grow as new
|
| 5 |
+
pages are scraped. This module merges them into the ``endomorphosis/ipfs_*_laws``
|
| 6 |
+
parquet schema without rewriting unchanged rows, so the GraphRAG builder can
|
| 7 |
+
delta-rebuild from the resulting pack.
|
| 8 |
+
|
| 9 |
+
Never invents legal text or identifiers. Empty/short bodies are dropped, not
|
| 10 |
+
filled.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
from datetime import datetime, timezone
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from typing import Any
|
| 20 |
+
|
| 21 |
+
import pandas as pd
|
| 22 |
+
|
| 23 |
+
from .cidutil import sha256_file
|
| 24 |
+
from .schema import LAW_FIELD_MAP, REQUIRED_ARTICLE_COLUMNS, REQUIRED_LAW_COLUMNS
|
| 25 |
+
|
| 26 |
+
LAW_COLS = [
|
| 27 |
+
"id",
|
| 28 |
+
"title",
|
| 29 |
+
"text",
|
| 30 |
+
"source_url",
|
| 31 |
+
"source_type",
|
| 32 |
+
"jurisdiction",
|
| 33 |
+
"country",
|
| 34 |
+
"language",
|
| 35 |
+
"eli",
|
| 36 |
+
"date",
|
| 37 |
+
"date_issued",
|
| 38 |
+
"retrieved_at",
|
| 39 |
+
"license",
|
| 40 |
+
"law_status",
|
| 41 |
+
"identifier",
|
| 42 |
+
"official_identifier",
|
| 43 |
+
"article_count",
|
| 44 |
+
"json_path",
|
| 45 |
+
"metadata_json",
|
| 46 |
+
]
|
| 47 |
+
ART_COLS = [
|
| 48 |
+
"law_id",
|
| 49 |
+
"id",
|
| 50 |
+
"title",
|
| 51 |
+
"text",
|
| 52 |
+
"source_url",
|
| 53 |
+
"document_number",
|
| 54 |
+
"article_number",
|
| 55 |
+
"record_type",
|
| 56 |
+
"metadata_json",
|
| 57 |
+
]
|
| 58 |
+
|
| 59 |
+
MIN_BODY_CHARS = 80
|
| 60 |
+
DEFAULT_CORPORA_ROOT = Path(
|
| 61 |
+
os.environ.get(
|
| 62 |
+
"LEGAL_CORPORA_ROOT",
|
| 63 |
+
str(Path.home() / ".ipfs_datasets" / "legal-corpora"),
|
| 64 |
+
)
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _s(value: Any) -> str:
|
| 69 |
+
if value is None:
|
| 70 |
+
return ""
|
| 71 |
+
return str(value).strip()
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _meta_json(value: Any) -> str:
|
| 75 |
+
if isinstance(value, str):
|
| 76 |
+
return value
|
| 77 |
+
try:
|
| 78 |
+
return json.dumps(value or {}, ensure_ascii=False)
|
| 79 |
+
except Exception:
|
| 80 |
+
return "{}"
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def instruments_to_frames(
|
| 84 |
+
instruments_dir: Path,
|
| 85 |
+
*,
|
| 86 |
+
min_body_chars: int = MIN_BODY_CHARS,
|
| 87 |
+
) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]:
|
| 88 |
+
"""Read collector JSON instruments into laws/articles dataframes."""
|
| 89 |
+
laws: list[dict[str, Any]] = []
|
| 90 |
+
arts: list[dict[str, Any]] = []
|
| 91 |
+
skipped_short = 0
|
| 92 |
+
skipped_bad = 0
|
| 93 |
+
root = Path(instruments_dir)
|
| 94 |
+
files = sorted(root.glob("*.json")) if root.is_dir() else []
|
| 95 |
+
for path in files:
|
| 96 |
+
try:
|
| 97 |
+
rec = json.loads(path.read_text(encoding="utf-8"))
|
| 98 |
+
except Exception:
|
| 99 |
+
skipped_bad += 1
|
| 100 |
+
continue
|
| 101 |
+
if not isinstance(rec, dict):
|
| 102 |
+
skipped_bad += 1
|
| 103 |
+
continue
|
| 104 |
+
text = _s(rec.get("text"))
|
| 105 |
+
ident = _s(rec.get("id"))
|
| 106 |
+
title = _s(rec.get("title"))
|
| 107 |
+
if not ident or not title or len(text) < min_body_chars:
|
| 108 |
+
skipped_short += 1
|
| 109 |
+
continue
|
| 110 |
+
meta = rec.get("metadata") or {}
|
| 111 |
+
laws.append(
|
| 112 |
+
{
|
| 113 |
+
"id": ident,
|
| 114 |
+
"title": title,
|
| 115 |
+
"text": text,
|
| 116 |
+
"source_url": _s(rec.get("source_url")),
|
| 117 |
+
"source_type": _s(rec.get("source_type")),
|
| 118 |
+
"jurisdiction": _s(rec.get("jurisdiction")),
|
| 119 |
+
"country": _s(rec.get("country")),
|
| 120 |
+
"language": _s(rec.get("language")),
|
| 121 |
+
"eli": _s(rec.get("eli")) or None,
|
| 122 |
+
"date": _s(rec.get("date")) or None,
|
| 123 |
+
"date_issued": _s(rec.get("date_issued") or rec.get("date")) or None,
|
| 124 |
+
"retrieved_at": _s(rec.get("retrieved_at")) or None,
|
| 125 |
+
"license": _s(rec.get("license")),
|
| 126 |
+
"law_status": _s(rec.get("law_status")),
|
| 127 |
+
"identifier": _s(rec.get("identifier")) or ident,
|
| 128 |
+
"official_identifier": _s(rec.get("official_identifier")),
|
| 129 |
+
"article_count": rec.get("article_count") or len(rec.get("documents") or []),
|
| 130 |
+
"json_path": f"instruments/{path.name}",
|
| 131 |
+
"metadata_json": _meta_json(meta),
|
| 132 |
+
}
|
| 133 |
+
)
|
| 134 |
+
for doc in rec.get("documents") or []:
|
| 135 |
+
if not isinstance(doc, dict):
|
| 136 |
+
continue
|
| 137 |
+
art_id = _s(doc.get("id"))
|
| 138 |
+
art_title = _s(doc.get("title"))
|
| 139 |
+
art_text = _s(doc.get("text"))
|
| 140 |
+
if not art_id or not art_title or not art_text:
|
| 141 |
+
continue
|
| 142 |
+
arts.append(
|
| 143 |
+
{
|
| 144 |
+
"law_id": ident,
|
| 145 |
+
"id": art_id,
|
| 146 |
+
"title": art_title,
|
| 147 |
+
"text": art_text,
|
| 148 |
+
"source_url": _s(doc.get("source_url")) or _s(rec.get("source_url")),
|
| 149 |
+
"document_number": _s(doc.get("document_number")),
|
| 150 |
+
"article_number": _s(doc.get("article_number")),
|
| 151 |
+
"record_type": _s(doc.get("record_type")) or "article",
|
| 152 |
+
"metadata_json": _meta_json(doc.get("metadata") or {}),
|
| 153 |
+
}
|
| 154 |
+
)
|
| 155 |
+
report = {
|
| 156 |
+
"n_instrument_files": len(files),
|
| 157 |
+
"n_laws": len(laws),
|
| 158 |
+
"n_articles": len(arts),
|
| 159 |
+
"skipped_short_or_empty": skipped_short,
|
| 160 |
+
"skipped_unreadable": skipped_bad,
|
| 161 |
+
"min_body_chars": min_body_chars,
|
| 162 |
+
"never_invented_legal_text": True,
|
| 163 |
+
"required_law_columns": list(REQUIRED_LAW_COLUMNS),
|
| 164 |
+
"required_article_columns": list(REQUIRED_ARTICLE_COLUMNS),
|
| 165 |
+
"law_field_map": dict(LAW_FIELD_MAP),
|
| 166 |
+
}
|
| 167 |
+
return (
|
| 168 |
+
pd.DataFrame(laws, columns=LAW_COLS),
|
| 169 |
+
pd.DataFrame(arts, columns=ART_COLS),
|
| 170 |
+
report,
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def _retrieved_key(value: Any) -> str:
|
| 175 |
+
return _s(value)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def merge_laws(prior: pd.DataFrame | None, incoming: pd.DataFrame) -> pd.DataFrame:
|
| 179 |
+
"""Upsert laws by ``id``. Newer ``retrieved_at`` wins; otherwise incoming wins."""
|
| 180 |
+
if prior is None or prior.empty:
|
| 181 |
+
return incoming.copy() if incoming is not None else pd.DataFrame(columns=LAW_COLS)
|
| 182 |
+
if incoming is None or incoming.empty:
|
| 183 |
+
return prior.copy()
|
| 184 |
+
by_id: dict[str, dict[str, Any]] = {}
|
| 185 |
+
for frame, incoming_flag in ((prior, False), (incoming, True)):
|
| 186 |
+
for rec in frame.to_dict(orient="records"):
|
| 187 |
+
ident = _s(rec.get("id"))
|
| 188 |
+
if not ident:
|
| 189 |
+
continue
|
| 190 |
+
existing = by_id.get(ident)
|
| 191 |
+
if existing is None:
|
| 192 |
+
by_id[ident] = rec
|
| 193 |
+
continue
|
| 194 |
+
if incoming_flag:
|
| 195 |
+
new_ts = _retrieved_key(rec.get("retrieved_at"))
|
| 196 |
+
old_ts = _retrieved_key(existing.get("retrieved_at"))
|
| 197 |
+
if not old_ts or new_ts >= old_ts:
|
| 198 |
+
by_id[ident] = rec
|
| 199 |
+
rows = [by_id[k] for k in sorted(by_id)]
|
| 200 |
+
return pd.DataFrame(rows, columns=LAW_COLS)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def merge_articles(prior: pd.DataFrame | None, incoming: pd.DataFrame) -> pd.DataFrame:
|
| 204 |
+
"""Upsert articles by ``id``. Incoming replaces the same article id."""
|
| 205 |
+
if prior is None or prior.empty:
|
| 206 |
+
return incoming.copy() if incoming is not None else pd.DataFrame(columns=ART_COLS)
|
| 207 |
+
if incoming is None or incoming.empty:
|
| 208 |
+
return prior.copy()
|
| 209 |
+
by_id: dict[str, dict[str, Any]] = {}
|
| 210 |
+
for frame in (prior, incoming):
|
| 211 |
+
for rec in frame.to_dict(orient="records"):
|
| 212 |
+
ident = _s(rec.get("id"))
|
| 213 |
+
if not ident:
|
| 214 |
+
continue
|
| 215 |
+
by_id[ident] = rec
|
| 216 |
+
rows = [by_id[k] for k in sorted(by_id)]
|
| 217 |
+
return pd.DataFrame(rows, columns=ART_COLS)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def load_existing_parquet(pack_dir: Path) -> tuple[pd.DataFrame | None, pd.DataFrame | None]:
|
| 221 |
+
pack_dir = Path(pack_dir)
|
| 222 |
+
laws_path = None
|
| 223 |
+
arts_path = None
|
| 224 |
+
for cand in (pack_dir / "data" / "laws.parquet", pack_dir / "laws.parquet"):
|
| 225 |
+
if cand.is_file():
|
| 226 |
+
laws_path = cand
|
| 227 |
+
break
|
| 228 |
+
for cand in (pack_dir / "data" / "articles.parquet", pack_dir / "articles.parquet"):
|
| 229 |
+
if cand.is_file():
|
| 230 |
+
arts_path = cand
|
| 231 |
+
break
|
| 232 |
+
laws = pd.read_parquet(laws_path) if laws_path else None
|
| 233 |
+
arts = pd.read_parquet(arts_path) if arts_path else None
|
| 234 |
+
return laws, arts
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def write_pack(
|
| 238 |
+
out: Path,
|
| 239 |
+
laws: pd.DataFrame,
|
| 240 |
+
articles: pd.DataFrame,
|
| 241 |
+
*,
|
| 242 |
+
slug: str,
|
| 243 |
+
source_dataset: str,
|
| 244 |
+
name: str | None = None,
|
| 245 |
+
extra_meta: dict[str, Any] | None = None,
|
| 246 |
+
) -> dict[str, Any]:
|
| 247 |
+
"""Write a local pack that ``load_source`` / ``get_country`` can consume."""
|
| 248 |
+
out = Path(out)
|
| 249 |
+
data_dir = out / "data"
|
| 250 |
+
data_dir.mkdir(parents=True, exist_ok=True)
|
| 251 |
+
laws_path = data_dir / "laws.parquet"
|
| 252 |
+
arts_path = data_dir / "articles.parquet"
|
| 253 |
+
laws.to_parquet(laws_path, index=False)
|
| 254 |
+
articles.to_parquet(arts_path, index=False)
|
| 255 |
+
now = datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
|
| 256 |
+
meta = {
|
| 257 |
+
"slug": slug,
|
| 258 |
+
"repo": source_dataset,
|
| 259 |
+
"source_dataset": source_dataset,
|
| 260 |
+
"name": name or slug.replace("_", " ").title(),
|
| 261 |
+
"indexable": True,
|
| 262 |
+
"source_revision": f"local:{now}",
|
| 263 |
+
"n_laws": int(len(laws)),
|
| 264 |
+
"n_articles": int(len(articles)),
|
| 265 |
+
"laws_sha256": sha256_file(laws_path),
|
| 266 |
+
"articles_sha256": sha256_file(arts_path),
|
| 267 |
+
"generated_at": now,
|
| 268 |
+
"incremental": True,
|
| 269 |
+
}
|
| 270 |
+
if extra_meta:
|
| 271 |
+
meta.update(extra_meta)
|
| 272 |
+
(out / "pack_meta.json").write_text(
|
| 273 |
+
json.dumps(meta, indent=2, ensure_ascii=False) + "\n",
|
| 274 |
+
encoding="utf-8",
|
| 275 |
+
)
|
| 276 |
+
return meta
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def package_instruments(
|
| 280 |
+
*,
|
| 281 |
+
instruments_dir: Path,
|
| 282 |
+
out: Path,
|
| 283 |
+
slug: str,
|
| 284 |
+
source_dataset: str | None = None,
|
| 285 |
+
prior_pack: Path | None = None,
|
| 286 |
+
name: str | None = None,
|
| 287 |
+
min_body_chars: int = MIN_BODY_CHARS,
|
| 288 |
+
) -> dict[str, Any]:
|
| 289 |
+
"""Merge collector JSON (+ optional prior parquet) into a local IR source pack."""
|
| 290 |
+
incoming_laws, incoming_arts, extract_report = instruments_to_frames(
|
| 291 |
+
instruments_dir, min_body_chars=min_body_chars
|
| 292 |
+
)
|
| 293 |
+
prior_laws = prior_arts = None
|
| 294 |
+
prior_dir = Path(prior_pack) if prior_pack else (out if out.exists() else None)
|
| 295 |
+
if prior_dir is not None:
|
| 296 |
+
prior_laws, prior_arts = load_existing_parquet(prior_dir)
|
| 297 |
+
laws = merge_laws(prior_laws, incoming_laws)
|
| 298 |
+
articles = merge_articles(prior_arts, incoming_arts)
|
| 299 |
+
if laws.empty:
|
| 300 |
+
raise RuntimeError(
|
| 301 |
+
f"no laws with text>={min_body_chars} under {instruments_dir}"
|
| 302 |
+
)
|
| 303 |
+
repo = source_dataset or f"endomorphosis/ipfs_{slug}_laws"
|
| 304 |
+
meta = write_pack(
|
| 305 |
+
out,
|
| 306 |
+
laws,
|
| 307 |
+
articles,
|
| 308 |
+
slug=slug,
|
| 309 |
+
source_dataset=repo,
|
| 310 |
+
name=name,
|
| 311 |
+
extra_meta={"extract": extract_report},
|
| 312 |
+
)
|
| 313 |
+
meta["extract"] = extract_report
|
| 314 |
+
meta["n_laws_prior"] = int(len(prior_laws)) if prior_laws is not None else 0
|
| 315 |
+
meta["n_articles_prior"] = int(len(prior_arts)) if prior_arts is not None else 0
|
| 316 |
+
meta["n_laws_incoming"] = int(len(incoming_laws))
|
| 317 |
+
meta["n_articles_incoming"] = int(len(incoming_arts))
|
| 318 |
+
meta["out"] = str(out)
|
| 319 |
+
return meta
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def default_instruments_dir(iso_or_slug: str, root: Path | None = None) -> Path:
|
| 323 |
+
base = Path(root) if root is not None else DEFAULT_CORPORA_ROOT
|
| 324 |
+
return base / iso_or_slug / "instruments"
|
country_laws_ir/sparse.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Country-law sparse GraphRAG export through the shared HF GraphRAG builders.
|
| 2 |
+
|
| 3 |
+
This is the same parquet layout used by US Code, state laws, Federal Register,
|
| 4 |
+
and SkillCenter:
|
| 5 |
+
|
| 6 |
+
* ``ipfs_datasets_py.retrieval.hf_graphrag.bm25.build_bm25_layout``
|
| 7 |
+
* ``ipfs_datasets_py.retrieval.hf_graphrag.graph.write_graph_layout``
|
| 8 |
+
|
| 9 |
+
No SQLite. Indexes are ZSTD parquet shards under ``data/bm25`` and
|
| 10 |
+
``data/graph``. DuckDB queries those shards at read time.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from typing import Any
|
| 17 |
+
|
| 18 |
+
import pandas as pd
|
| 19 |
+
|
| 20 |
+
from . import EDGE_IDENTITY_SCHEMA, SCHEMA_VERSION
|
| 21 |
+
from .cidutil import cid_of_json
|
| 22 |
+
from .graph import build_graph
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def corpus_to_bm25_rows(corpus: pd.DataFrame) -> list[dict[str, Any]]:
|
| 26 |
+
"""Project a normalized country-law corpus onto the shared BM25 row schema."""
|
| 27 |
+
rows: list[dict[str, Any]] = []
|
| 28 |
+
for rec in corpus.itertuples(index=False):
|
| 29 |
+
rows.append(
|
| 30 |
+
{
|
| 31 |
+
"entry_cid": str(rec.entry_cid),
|
| 32 |
+
"title": str(getattr(rec, "title", "") or ""),
|
| 33 |
+
"body": str(getattr(rec, "body", "") or ""),
|
| 34 |
+
"record_type": str(getattr(rec, "record_type", "") or "law"),
|
| 35 |
+
"document_index": int(rec.document_index),
|
| 36 |
+
}
|
| 37 |
+
)
|
| 38 |
+
return rows
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _graph_nodes_and_edges(corpus: pd.DataFrame) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
| 42 |
+
"""Structural graph only (no precomputed BM25 neighbor matrix)."""
|
| 43 |
+
built = build_graph(corpus, [[] for _ in range(len(corpus))])
|
| 44 |
+
nodes = [
|
| 45 |
+
{
|
| 46 |
+
"node_cid": str(row["node_cid"]),
|
| 47 |
+
"node_type": str(row["node_type"]),
|
| 48 |
+
"label": row.get("label"),
|
| 49 |
+
"entry_cid": row.get("entry_cid") or None,
|
| 50 |
+
}
|
| 51 |
+
for row in built["nodes"].to_dict("records")
|
| 52 |
+
]
|
| 53 |
+
edges = []
|
| 54 |
+
for row in built["edges"].to_dict("records"):
|
| 55 |
+
source = str(row.get("source_cid") or row.get("source_node_cid") or "")
|
| 56 |
+
target = str(row.get("target_cid") or row.get("target_node_cid") or "")
|
| 57 |
+
edge_type = str(row.get("edge_type") or "")
|
| 58 |
+
if not source or not target or not edge_type:
|
| 59 |
+
continue
|
| 60 |
+
edge_cid = str(row.get("edge_cid") or "") or cid_of_json(
|
| 61 |
+
{
|
| 62 |
+
"edge_type": edge_type,
|
| 63 |
+
"schema": EDGE_IDENTITY_SCHEMA,
|
| 64 |
+
"source": source,
|
| 65 |
+
"target": target,
|
| 66 |
+
}
|
| 67 |
+
)
|
| 68 |
+
edges.append(
|
| 69 |
+
{
|
| 70 |
+
"edge_cid": edge_cid,
|
| 71 |
+
"edge_type": edge_type,
|
| 72 |
+
"source_node_cid": source,
|
| 73 |
+
"target_node_cid": target,
|
| 74 |
+
"retrieval_method": str(row.get("retrieval_method") or "structural"),
|
| 75 |
+
"score": row.get("score"),
|
| 76 |
+
}
|
| 77 |
+
)
|
| 78 |
+
return nodes, edges
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def export_sparse_graphrag(
|
| 82 |
+
corpus: pd.DataFrame,
|
| 83 |
+
output_dir: Path,
|
| 84 |
+
) -> dict[str, Any]:
|
| 85 |
+
"""Write BM25 + graph parquet shards using the shared HF GraphRAG builders."""
|
| 86 |
+
from ipfs_datasets_py.retrieval.hf_graphrag.bm25 import (
|
| 87 |
+
BM25LayoutConfig,
|
| 88 |
+
build_bm25_layout,
|
| 89 |
+
)
|
| 90 |
+
from ipfs_datasets_py.retrieval.hf_graphrag.graph import write_graph_layout
|
| 91 |
+
|
| 92 |
+
output_dir = Path(output_dir)
|
| 93 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 94 |
+
rows = corpus_to_bm25_rows(corpus)
|
| 95 |
+
bm25 = build_bm25_layout(
|
| 96 |
+
rows,
|
| 97 |
+
output_dir,
|
| 98 |
+
config=BM25LayoutConfig(max_documents=max(len(rows), 1)),
|
| 99 |
+
)
|
| 100 |
+
nodes, edges = _graph_nodes_and_edges(corpus)
|
| 101 |
+
written = write_graph_layout(nodes, edges, output_dir)
|
| 102 |
+
layout = written.layout
|
| 103 |
+
return {
|
| 104 |
+
"engine": "hf_graphrag",
|
| 105 |
+
"schema_version": SCHEMA_VERSION,
|
| 106 |
+
"bm25": bm25.to_manifest_fragment(),
|
| 107 |
+
"graph": {
|
| 108 |
+
"node_count": int(layout.node_count),
|
| 109 |
+
"edge_count": int(layout.edge_count),
|
| 110 |
+
"adjacency": "data/graph/adjacency/{out,in}/*.parquet",
|
| 111 |
+
},
|
| 112 |
+
"sqlite": False,
|
| 113 |
+
"query_engine": "duckdb",
|
| 114 |
+
}
|
country_laws_ir/spill.py
CHANGED
|
@@ -1,17 +1,15 @@
|
|
| 1 |
-
"""Disk-spill helpers for large country IR builds (
|
| 2 |
|
| 3 |
Design (CoS / DO OOM lesson):
|
| 4 |
- Embeddings: checkpointed .npy via vectors.encode_corpus (unchanged).
|
| 5 |
-
- Neighbors for n >=
|
| 6 |
-
into neighbor_*.
|
| 7 |
-
|
| 8 |
-
- BM25 TF: stream tokenize →
|
| 9 |
-
- Package:
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
Resume-safe: existing FTS DB / neighbor shards / bm25_*.parquet are reused when
|
| 14 |
-
row counts match.
|
| 15 |
"""
|
| 16 |
from __future__ import annotations
|
| 17 |
|
|
@@ -19,7 +17,6 @@ import gc
|
|
| 19 |
import json
|
| 20 |
import math
|
| 21 |
import pickle
|
| 22 |
-
import sqlite3
|
| 23 |
from collections import defaultdict
|
| 24 |
from pathlib import Path
|
| 25 |
from typing import Any, Callable, Iterable, Iterator
|
|
@@ -41,7 +38,8 @@ from .graph import _adjacency, _edge, build_graph
|
|
| 41 |
from .mem import MemAbort, checkpoint, log_mem
|
| 42 |
from .tokenize import tokenize
|
| 43 |
|
| 44 |
-
|
|
|
|
| 45 |
BATCH = 256
|
| 46 |
NEIGHBOR_SHARD = 5_000
|
| 47 |
NEIGHBOR_K = 8
|
|
@@ -68,19 +66,24 @@ def load_pickle(path: Path) -> Any:
|
|
| 68 |
return pickle.load(f)
|
| 69 |
|
| 70 |
|
| 71 |
-
def quote_fts_term(term: str) -> str:
|
| 72 |
-
return '"' + term.replace('"', '""') + '"'
|
| 73 |
-
|
| 74 |
-
|
| 75 |
def _idf(n_docs: int, df: int) -> float:
|
| 76 |
return math.log((n_docs - df + 0.5) / (df + 0.5) + 1.0)
|
| 77 |
|
| 78 |
|
| 79 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
if not db_path.is_file():
|
| 81 |
return False
|
|
|
|
| 82 |
try:
|
| 83 |
-
conn =
|
| 84 |
n = int(conn.execute("SELECT COUNT(*) FROM documents").fetchone()[0])
|
| 85 |
conn.close()
|
| 86 |
return n == expected
|
|
@@ -88,265 +91,49 @@ def sqlite_ready(db_path: Path, expected: int) -> bool:
|
|
| 88 |
return False
|
| 89 |
|
| 90 |
|
| 91 |
-
def build_sqlite_fts(
|
| 92 |
-
|
| 93 |
-
db_path: Path,
|
| 94 |
-
expected: int,
|
| 95 |
-
*,
|
| 96 |
-
batch: int = BATCH,
|
| 97 |
-
log: Callable[[str], None] | None = None,
|
| 98 |
-
) -> int:
|
| 99 |
-
"""Contentless FTS5 over title+body; documents table holds query_text."""
|
| 100 |
-
if db_path.exists():
|
| 101 |
-
db_path.unlink()
|
| 102 |
-
db_path.parent.mkdir(parents=True, exist_ok=True)
|
| 103 |
-
conn = sqlite3.connect(str(db_path))
|
| 104 |
-
try:
|
| 105 |
-
conn.executescript(
|
| 106 |
-
"""
|
| 107 |
-
PRAGMA journal_mode = OFF;
|
| 108 |
-
PRAGMA synchronous = OFF;
|
| 109 |
-
PRAGMA temp_store = MEMORY;
|
| 110 |
-
PRAGMA locking_mode = EXCLUSIVE;
|
| 111 |
-
PRAGMA page_size = 32768;
|
| 112 |
-
CREATE TABLE documents (
|
| 113 |
-
document_index INTEGER PRIMARY KEY,
|
| 114 |
-
entry_cid TEXT NOT NULL UNIQUE,
|
| 115 |
-
title TEXT NOT NULL,
|
| 116 |
-
query_text TEXT NOT NULL
|
| 117 |
-
);
|
| 118 |
-
CREATE VIRTUAL TABLE documents_fts USING fts5(
|
| 119 |
-
title,
|
| 120 |
-
body,
|
| 121 |
-
content='',
|
| 122 |
-
columnsize=1,
|
| 123 |
-
tokenize='unicode61 remove_diacritics 2'
|
| 124 |
-
);
|
| 125 |
-
"""
|
| 126 |
-
)
|
| 127 |
-
pf = pq.ParquetFile(corpus_path)
|
| 128 |
-
n = 0
|
| 129 |
-
meta_batch: list[tuple] = []
|
| 130 |
-
fts_batch: list[tuple] = []
|
| 131 |
-
conn.execute("BEGIN")
|
| 132 |
-
for batch_tbl in pf.iter_batches(
|
| 133 |
-
batch_size=batch, columns=["document_index", "entry_cid", "title", "body"]
|
| 134 |
-
):
|
| 135 |
-
cols = batch_tbl.to_pydict()
|
| 136 |
-
for i in range(len(cols["document_index"])):
|
| 137 |
-
di = int(cols["document_index"][i])
|
| 138 |
-
title = str(cols["title"][i] or "")
|
| 139 |
-
body = str(cols["body"][i] or "")
|
| 140 |
-
cid = str(cols["entry_cid"][i])
|
| 141 |
-
qtext = title.strip() if title.strip() else body[:800]
|
| 142 |
-
meta_batch.append((di, cid, title, qtext))
|
| 143 |
-
fts_batch.append((di + 1, title, body))
|
| 144 |
-
if len(meta_batch) >= batch:
|
| 145 |
-
conn.executemany(
|
| 146 |
-
"INSERT INTO documents(document_index, entry_cid, title, query_text) "
|
| 147 |
-
"VALUES (?,?,?,?)",
|
| 148 |
-
meta_batch,
|
| 149 |
-
)
|
| 150 |
-
conn.executemany(
|
| 151 |
-
"INSERT INTO documents_fts(rowid, title, body) VALUES (?,?,?)",
|
| 152 |
-
fts_batch,
|
| 153 |
-
)
|
| 154 |
-
n += len(meta_batch)
|
| 155 |
-
meta_batch.clear()
|
| 156 |
-
fts_batch.clear()
|
| 157 |
-
if n % 20_000 == 0:
|
| 158 |
-
checkpoint(f"fts_insert@{n}", row=n, every_n=20_000, log=log)
|
| 159 |
-
gc.collect()
|
| 160 |
-
if meta_batch:
|
| 161 |
-
conn.executemany(
|
| 162 |
-
"INSERT INTO documents(document_index, entry_cid, title, query_text) "
|
| 163 |
-
"VALUES (?,?,?,?)",
|
| 164 |
-
meta_batch,
|
| 165 |
-
)
|
| 166 |
-
conn.executemany(
|
| 167 |
-
"INSERT INTO documents_fts(rowid, title, body) VALUES (?,?,?)",
|
| 168 |
-
fts_batch,
|
| 169 |
-
)
|
| 170 |
-
n += len(meta_batch)
|
| 171 |
-
conn.commit()
|
| 172 |
-
conn.execute("INSERT INTO documents_fts(documents_fts) VALUES('optimize')")
|
| 173 |
-
conn.commit()
|
| 174 |
-
conn.execute(
|
| 175 |
-
"CREATE VIRTUAL TABLE documents_vocab USING fts5vocab(documents_fts, 'row')"
|
| 176 |
-
)
|
| 177 |
-
conn.commit()
|
| 178 |
-
got = int(conn.execute("SELECT COUNT(*) FROM documents").fetchone()[0])
|
| 179 |
-
assert got == n == expected, (got, n, expected)
|
| 180 |
-
return n
|
| 181 |
-
except Exception:
|
| 182 |
-
conn.rollback()
|
| 183 |
-
raise
|
| 184 |
-
finally:
|
| 185 |
-
conn.close()
|
| 186 |
-
gc.collect()
|
| 187 |
|
| 188 |
|
| 189 |
-
def
|
| 190 |
-
|
| 191 |
-
for term, doc in conn.execute(
|
| 192 |
-
"SELECT term, doc FROM documents_vocab WHERE doc <= ?", (df_cap,)
|
| 193 |
-
):
|
| 194 |
-
df_map[str(term)] = int(doc)
|
| 195 |
-
return df_map
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
def select_query_terms(query_text: str, df_map: dict[str, int]) -> list[str]:
|
| 199 |
-
toks = tokenize(query_text)[:24]
|
| 200 |
-
seen: set[str] = set()
|
| 201 |
-
cands: list[tuple[int, str]] = []
|
| 202 |
-
for t in toks:
|
| 203 |
-
if t in seen or len(t) < 2:
|
| 204 |
-
continue
|
| 205 |
-
seen.add(t)
|
| 206 |
-
if t not in df_map:
|
| 207 |
-
continue
|
| 208 |
-
cands.append((df_map[t], t))
|
| 209 |
-
cands.sort()
|
| 210 |
-
return [t for _, t in cands[:MAX_QTERMS]]
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
def stream_neighbors_to_shards(
|
| 214 |
-
db_path: Path,
|
| 215 |
spill: Path,
|
| 216 |
n_docs: int,
|
| 217 |
*,
|
| 218 |
k: int = NEIGHBOR_K,
|
| 219 |
-
shard: int = NEIGHBOR_SHARD,
|
| 220 |
-
batch: int = BATCH,
|
| 221 |
-
df_cap: int = DF_CAP,
|
| 222 |
resume: bool = True,
|
| 223 |
log: Callable[[str], None] | None = None,
|
| 224 |
) -> list[Path]:
|
| 225 |
-
"""
|
|
|
|
| 226 |
|
| 227 |
-
|
| 228 |
-
whose end index is covered (contiguous from 0).
|
| 229 |
-
"""
|
| 230 |
spill.mkdir(parents=True, exist_ok=True)
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
# Contiguous cover from 0
|
| 236 |
-
covered = 0
|
| 237 |
-
for sp in existing:
|
| 238 |
-
parts = sp.stem.split("_")
|
| 239 |
-
# neighbors_000000_005000
|
| 240 |
-
try:
|
| 241 |
-
start_i, end_i = int(parts[1]), int(parts[2])
|
| 242 |
-
except (IndexError, ValueError):
|
| 243 |
-
continue
|
| 244 |
-
if start_i != covered:
|
| 245 |
-
break
|
| 246 |
-
shard_paths.append(sp)
|
| 247 |
-
covered = end_i
|
| 248 |
-
buf_start = covered
|
| 249 |
-
if buf_start >= n_docs:
|
| 250 |
-
if log:
|
| 251 |
-
log(f"neighbors resume complete {buf_start}/{n_docs}")
|
| 252 |
-
return shard_paths
|
| 253 |
if log:
|
| 254 |
-
log(f"
|
| 255 |
-
|
| 256 |
-
for sp in existing:
|
| 257 |
-
if sp not in shard_paths:
|
| 258 |
-
sp.unlink(missing_ok=True)
|
| 259 |
else:
|
| 260 |
-
for sp in existing:
|
| 261 |
-
sp.unlink(missing_ok=True)
|
| 262 |
-
|
| 263 |
-
conn_rw = sqlite3.connect(str(db_path))
|
| 264 |
-
row = conn_rw.execute(
|
| 265 |
-
"SELECT name FROM sqlite_master WHERE name='documents_vocab'"
|
| 266 |
-
).fetchone()
|
| 267 |
-
if row is None:
|
| 268 |
-
conn_rw.execute(
|
| 269 |
-
"CREATE VIRTUAL TABLE documents_vocab USING fts5vocab(documents_fts, 'row')"
|
| 270 |
-
)
|
| 271 |
-
conn_rw.commit()
|
| 272 |
-
df_map = load_df_map(conn_rw, df_cap)
|
| 273 |
-
conn_rw.close()
|
| 274 |
-
spill_pickle(spill / "df_map_meta.pkl", {"n_rare": len(df_map), "df_cap": df_cap})
|
| 275 |
-
if log:
|
| 276 |
-
log(f"vocab rare_terms={len(df_map)} df_cap={df_cap}")
|
| 277 |
-
|
| 278 |
-
conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
|
| 279 |
-
conn.row_factory = sqlite3.Row
|
| 280 |
-
buf: list = []
|
| 281 |
-
done = buf_start
|
| 282 |
-
score_sql = f"-bm25(documents_fts, {TITLE_W}, {BODY_W})"
|
| 283 |
-
last_idx = buf_start - 1
|
| 284 |
-
try:
|
| 285 |
-
while True:
|
| 286 |
-
rows = conn.execute(
|
| 287 |
-
"SELECT document_index, entry_cid, query_text FROM documents "
|
| 288 |
-
"WHERE document_index > ? ORDER BY document_index LIMIT ?",
|
| 289 |
-
(last_idx, batch),
|
| 290 |
-
).fetchall()
|
| 291 |
-
if not rows:
|
| 292 |
-
break
|
| 293 |
-
for row in rows:
|
| 294 |
-
di = int(row["document_index"])
|
| 295 |
-
terms = select_query_terms(str(row["query_text"]), df_map)
|
| 296 |
-
if not terms:
|
| 297 |
-
neigh: list = []
|
| 298 |
-
else:
|
| 299 |
-
expr = " OR ".join("title : " + quote_fts_term(t) for t in terms)
|
| 300 |
-
sql = (
|
| 301 |
-
"SELECT d.document_index, " + score_sql + " AS score "
|
| 302 |
-
"FROM documents_fts "
|
| 303 |
-
"JOIN documents AS d ON d.document_index = documents_fts.rowid - 1 "
|
| 304 |
-
"WHERE documents_fts MATCH ? AND d.document_index != ? "
|
| 305 |
-
"ORDER BY score DESC, d.document_index LIMIT ?"
|
| 306 |
-
)
|
| 307 |
-
hits = conn.execute(sql, (expr, di, k)).fetchall()
|
| 308 |
-
neigh = [
|
| 309 |
-
(int(h["document_index"]), max(0.0, float(h["score"])), list(terms)[:4])
|
| 310 |
-
for h in hits
|
| 311 |
-
]
|
| 312 |
-
while buf_start + len(buf) < di:
|
| 313 |
-
buf.append([])
|
| 314 |
-
buf.append(neigh)
|
| 315 |
-
last_idx = di
|
| 316 |
-
done += 1
|
| 317 |
-
if len(buf) >= shard:
|
| 318 |
-
end = buf_start + len(buf)
|
| 319 |
-
sp = spill / f"neighbors_{buf_start:06d}_{end:06d}.pkl"
|
| 320 |
-
spill_pickle(sp, buf)
|
| 321 |
-
shard_paths.append(sp)
|
| 322 |
-
checkpoint(
|
| 323 |
-
f"neighbors_shard_{buf_start}_{end}",
|
| 324 |
-
log=log,
|
| 325 |
-
)
|
| 326 |
-
buf_start = end
|
| 327 |
-
buf = []
|
| 328 |
-
gc.collect()
|
| 329 |
-
if done % 5_000 == 0:
|
| 330 |
-
checkpoint(f"neighbors_stream", row=done, every_n=5_000, log=log)
|
| 331 |
-
if buf:
|
| 332 |
-
end = buf_start + len(buf)
|
| 333 |
-
sp = spill / f"neighbors_{buf_start:06d}_{end:06d}.pkl"
|
| 334 |
-
spill_pickle(sp, buf)
|
| 335 |
-
shard_paths.append(sp)
|
| 336 |
-
if log:
|
| 337 |
-
log(f"neighbors shard final {buf_start}:{end}/{n_docs}")
|
| 338 |
if log:
|
| 339 |
-
log(f"
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
del df_map
|
| 344 |
-
gc.collect()
|
| 345 |
|
| 346 |
|
| 347 |
def iter_neighbor_shards(spill: Path) -> Iterator[tuple[int, list]]:
|
| 348 |
-
"""Yield (start_index, shard_list)
|
| 349 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 350 |
for sp in paths:
|
| 351 |
parts = sp.stem.split("_")
|
| 352 |
start_i = int(parts[1])
|
|
@@ -369,30 +156,9 @@ def assemble_neighbors_streaming(spill: Path, n_docs: int) -> list:
|
|
| 369 |
return neighbors
|
| 370 |
|
| 371 |
|
| 372 |
-
def neighbors_via_sqlite(
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
n_docs: int,
|
| 376 |
-
*,
|
| 377 |
-
k: int = NEIGHBOR_K,
|
| 378 |
-
resume: bool = True,
|
| 379 |
-
log: Callable[[str], None] | None = None,
|
| 380 |
-
) -> list[Path]:
|
| 381 |
-
"""Ensure FTS DB + neighbor shards; return shard paths (not full list)."""
|
| 382 |
-
spill.mkdir(parents=True, exist_ok=True)
|
| 383 |
-
db_path = spill / "fts.sqlite"
|
| 384 |
-
if not sqlite_ready(db_path, n_docs):
|
| 385 |
-
if db_path.exists():
|
| 386 |
-
db_path.unlink()
|
| 387 |
-
if log:
|
| 388 |
-
log(f"building sqlite fts n={n_docs} -> {db_path}")
|
| 389 |
-
build_sqlite_fts(corpus_path, db_path, n_docs, log=log)
|
| 390 |
-
else:
|
| 391 |
-
if log:
|
| 392 |
-
log(f"reusing sqlite fts n={n_docs} path={db_path}")
|
| 393 |
-
return stream_neighbors_to_shards(
|
| 394 |
-
db_path, spill, n_docs, k=k, resume=resume, log=log
|
| 395 |
-
)
|
| 396 |
|
| 397 |
|
| 398 |
def build_graph_from_neighbor_shards(
|
|
@@ -492,33 +258,35 @@ def build_bm25_tf_spill(
|
|
| 492 |
batch: int = 512,
|
| 493 |
log: Callable[[str], None] | None = None,
|
| 494 |
) -> dict[str, Any]:
|
| 495 |
-
"""Stream tokenize corpus →
|
| 496 |
|
| 497 |
-
Resume: if bm25_documents.parquet + bm25_postings.parquet + bm25_stats.
|
| 498 |
with matching n_docs, reuse.
|
| 499 |
"""
|
| 500 |
spill.mkdir(parents=True, exist_ok=True)
|
| 501 |
docs_path = spill / "bm25_documents.parquet"
|
| 502 |
post_path = spill / "bm25_postings.parquet"
|
|
|
|
| 503 |
stats_path = spill / "bm25_stats.pkl"
|
| 504 |
-
if docs_path.is_file() and post_path.is_file()
|
| 505 |
-
stats =
|
| 506 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
| 507 |
if log:
|
| 508 |
log(f"reusing bm25 spill n_docs={n_docs}")
|
| 509 |
return {"stats": stats, "documents": docs_path, "postings": post_path}
|
| 510 |
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
conn
|
| 516 |
-
conn.execute("PRAGMA synchronous=OFF")
|
| 517 |
-
conn.execute("PRAGMA temp_store=MEMORY")
|
| 518 |
-
conn.execute("PRAGMA locking_mode=EXCLUSIVE")
|
| 519 |
conn.execute(
|
| 520 |
-
"CREATE TABLE tf (term
|
| 521 |
-
"ttf INTEGER NOT NULL, btf INTEGER NOT NULL
|
| 522 |
)
|
| 523 |
title_len = np.zeros(n_docs, dtype=np.int32)
|
| 524 |
body_len = np.zeros(n_docs, dtype=np.int32)
|
|
@@ -549,7 +317,6 @@ def build_bm25_tf_spill(
|
|
| 549 |
]
|
| 550 |
processed = 0
|
| 551 |
batch_rows: list[tuple] = []
|
| 552 |
-
conn.execute("BEGIN")
|
| 553 |
for batch_tbl in pf.iter_batches(batch_size=batch, columns=cols):
|
| 554 |
d = batch_tbl.to_pydict()
|
| 555 |
m = len(d["document_index"])
|
|
@@ -593,9 +360,7 @@ def build_bm25_tf_spill(
|
|
| 593 |
}
|
| 594 |
)
|
| 595 |
if len(batch_rows) >= 20_000:
|
| 596 |
-
conn.executemany(
|
| 597 |
-
"INSERT OR REPLACE INTO tf VALUES (?,?,?,?)", batch_rows
|
| 598 |
-
)
|
| 599 |
batch_rows.clear()
|
| 600 |
processed += m
|
| 601 |
if len(meta_buf) >= 20_000:
|
|
@@ -612,7 +377,7 @@ def build_bm25_tf_spill(
|
|
| 612 |
checkpoint(f"bm25_tf_tokenize", row=processed, every_n=20_000, log=log)
|
| 613 |
gc.collect()
|
| 614 |
if batch_rows:
|
| 615 |
-
conn.executemany("INSERT
|
| 616 |
batch_rows.clear()
|
| 617 |
if meta_buf:
|
| 618 |
dfm = pd.DataFrame(meta_buf)
|
|
@@ -623,9 +388,8 @@ def build_bm25_tf_spill(
|
|
| 623 |
dfm.to_parquet(meta_path, index=False)
|
| 624 |
del dfm
|
| 625 |
meta_buf.clear()
|
| 626 |
-
conn.commit()
|
| 627 |
if log:
|
| 628 |
-
log("bm25 tf spilled; writing documents")
|
| 629 |
|
| 630 |
doc_len = (title_len * TITLE_WEIGHT + body_len * BODY_WEIGHT).astype(np.float64)
|
| 631 |
avgdl = float(doc_len.mean()) if n_docs else 0.0
|
|
@@ -696,7 +460,7 @@ def build_bm25_tf_spill(
|
|
| 696 |
|
| 697 |
for term, doc, ttf, btf in conn.execute(
|
| 698 |
"SELECT term, doc, ttf, btf FROM tf ORDER BY term, doc"
|
| 699 |
-
):
|
| 700 |
term = str(term)
|
| 701 |
if cur_term is None:
|
| 702 |
cur_term = term
|
|
@@ -749,9 +513,9 @@ def build_bm25_tf_spill(
|
|
| 749 |
"n_posting_rows": int(out_rows),
|
| 750 |
"n_postings": int(n_postings),
|
| 751 |
}
|
| 752 |
-
|
| 753 |
try:
|
| 754 |
-
|
| 755 |
except Exception:
|
| 756 |
pass
|
| 757 |
if log:
|
|
@@ -759,5 +523,10 @@ def build_bm25_tf_spill(
|
|
| 759 |
return {"stats": stats, "documents": docs_path, "postings": post_path}
|
| 760 |
|
| 761 |
|
| 762 |
-
def
|
| 763 |
return n_docs >= threshold
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Disk-spill helpers for large country IR builds (DuckDB + parquet).
|
| 2 |
|
| 3 |
Design (CoS / DO OOM lesson):
|
| 4 |
- Embeddings: checkpointed .npy via vectors.encode_corpus (unchanged).
|
| 5 |
+
- Neighbors for n >= DUCKDB_THRESHOLD (40k): DuckDB FTS over corpus parquet,
|
| 6 |
+
streamed into neighbor_*.parquet shards — never hold the full neighbor
|
| 7 |
+
matrix in RAM.
|
| 8 |
+
- BM25 TF: stream tokenize → DuckDB → posting parquet parts.
|
| 9 |
+
- Package: sequential parquet write so corpus, bm25, graph, vectors are never
|
| 10 |
+
all resident together.
|
| 11 |
+
|
| 12 |
+
No SQLite. Intermediate and published artifacts are parquet / DuckDB.
|
|
|
|
|
|
|
| 13 |
"""
|
| 14 |
from __future__ import annotations
|
| 15 |
|
|
|
|
| 17 |
import json
|
| 18 |
import math
|
| 19 |
import pickle
|
|
|
|
| 20 |
from collections import defaultdict
|
| 21 |
from pathlib import Path
|
| 22 |
from typing import Any, Callable, Iterable, Iterator
|
|
|
|
| 38 |
from .mem import MemAbort, checkpoint, log_mem
|
| 39 |
from .tokenize import tokenize
|
| 40 |
|
| 41 |
+
DUCKDB_THRESHOLD = 40_000
|
| 42 |
+
SQLITE_THRESHOLD = DUCKDB_THRESHOLD # backward-compatible alias; not SQLite
|
| 43 |
BATCH = 256
|
| 44 |
NEIGHBOR_SHARD = 5_000
|
| 45 |
NEIGHBOR_K = 8
|
|
|
|
| 66 |
return pickle.load(f)
|
| 67 |
|
| 68 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
def _idf(n_docs: int, df: int) -> float:
|
| 70 |
return math.log((n_docs - df + 0.5) / (df + 0.5) + 1.0)
|
| 71 |
|
| 72 |
|
| 73 |
+
def _require_duckdb():
|
| 74 |
+
try:
|
| 75 |
+
import duckdb # type: ignore
|
| 76 |
+
except ImportError as exc:
|
| 77 |
+
raise RuntimeError("duckdb is required for sparse GraphRAG spill (no sqlite)") from exc
|
| 78 |
+
return duckdb
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def duckdb_ready(db_path: Path, expected: int) -> bool:
|
| 82 |
if not db_path.is_file():
|
| 83 |
return False
|
| 84 |
+
duckdb = _require_duckdb()
|
| 85 |
try:
|
| 86 |
+
conn = duckdb.connect(str(db_path), read_only=True)
|
| 87 |
n = int(conn.execute("SELECT COUNT(*) FROM documents").fetchone()[0])
|
| 88 |
conn.close()
|
| 89 |
return n == expected
|
|
|
|
| 91 |
return False
|
| 92 |
|
| 93 |
|
| 94 |
+
def build_sqlite_fts(*args, **kwargs): # pragma: no cover - removed
|
| 95 |
+
raise RuntimeError("SQLite FTS is removed; use DuckDB parquet neighbors")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
|
| 98 |
+
def neighbors_via_duckdb(
|
| 99 |
+
corpus_path: Path,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
spill: Path,
|
| 101 |
n_docs: int,
|
| 102 |
*,
|
| 103 |
k: int = NEIGHBOR_K,
|
|
|
|
|
|
|
|
|
|
| 104 |
resume: bool = True,
|
| 105 |
log: Callable[[str], None] | None = None,
|
| 106 |
) -> list[Path]:
|
| 107 |
+
"""DuckDB FTS over corpus parquet → neighbor_*.parquet shards. No SQLite."""
|
| 108 |
+
from .duckdb_store import build_fts_index, stream_neighbors_to_parquet
|
| 109 |
|
| 110 |
+
spill = Path(spill)
|
|
|
|
|
|
|
| 111 |
spill.mkdir(parents=True, exist_ok=True)
|
| 112 |
+
db_path = spill / "neighbors.duckdb"
|
| 113 |
+
if not duckdb_ready(db_path, n_docs):
|
| 114 |
+
if db_path.exists():
|
| 115 |
+
db_path.unlink()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
if log:
|
| 117 |
+
log(f"building duckdb fts n={n_docs} -> {db_path}")
|
| 118 |
+
build_fts_index(corpus_path, db_path, n_docs, log=log)
|
|
|
|
|
|
|
|
|
|
| 119 |
else:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
if log:
|
| 121 |
+
log(f"reusing duckdb fts n={n_docs} path={db_path}")
|
| 122 |
+
return stream_neighbors_to_parquet(
|
| 123 |
+
db_path, spill, n_docs, k=k, resume=resume, log=log
|
| 124 |
+
)
|
|
|
|
|
|
|
| 125 |
|
| 126 |
|
| 127 |
def iter_neighbor_shards(spill: Path) -> Iterator[tuple[int, list]]:
|
| 128 |
+
"""Yield (start_index, shard_list) from parquet neighbor shards."""
|
| 129 |
+
from .duckdb_store import iter_neighbor_parquet_shards
|
| 130 |
+
|
| 131 |
+
parquet = list(Path(spill).glob("neighbors_*.parquet"))
|
| 132 |
+
if parquet:
|
| 133 |
+
yield from iter_neighbor_parquet_shards(spill)
|
| 134 |
+
return
|
| 135 |
+
# Legacy pickle shards (pre-DuckDB). Do not create new ones.
|
| 136 |
+
paths = sorted(Path(spill).glob("neighbors_*.pkl"))
|
| 137 |
for sp in paths:
|
| 138 |
parts = sp.stem.split("_")
|
| 139 |
start_i = int(parts[1])
|
|
|
|
| 156 |
return neighbors
|
| 157 |
|
| 158 |
|
| 159 |
+
def neighbors_via_sqlite(*args, **kwargs):
|
| 160 |
+
"""Removed. Sparse GraphRAG neighbors are DuckDB/parquet only."""
|
| 161 |
+
return neighbors_via_duckdb(*args, **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
|
| 163 |
|
| 164 |
def build_graph_from_neighbor_shards(
|
|
|
|
| 258 |
batch: int = 512,
|
| 259 |
log: Callable[[str], None] | None = None,
|
| 260 |
) -> dict[str, Any]:
|
| 261 |
+
"""Stream tokenize corpus → DuckDB TF → bm25_documents/postings parquet + stats.
|
| 262 |
|
| 263 |
+
Resume: if bm25_documents.parquet + bm25_postings.parquet + bm25_stats.json exist
|
| 264 |
with matching n_docs, reuse.
|
| 265 |
"""
|
| 266 |
spill.mkdir(parents=True, exist_ok=True)
|
| 267 |
docs_path = spill / "bm25_documents.parquet"
|
| 268 |
post_path = spill / "bm25_postings.parquet"
|
| 269 |
+
stats_json = spill / "bm25_stats.json"
|
| 270 |
stats_path = spill / "bm25_stats.pkl"
|
| 271 |
+
if docs_path.is_file() and post_path.is_file():
|
| 272 |
+
stats = None
|
| 273 |
+
if stats_json.is_file():
|
| 274 |
+
stats = json.loads(stats_json.read_text(encoding="utf-8"))
|
| 275 |
+
elif stats_path.is_file():
|
| 276 |
+
stats = load_pickle(stats_path)
|
| 277 |
+
if stats is not None and int(stats.get("n_docs", -1)) == n_docs:
|
| 278 |
if log:
|
| 279 |
log(f"reusing bm25 spill n_docs={n_docs}")
|
| 280 |
return {"stats": stats, "documents": docs_path, "postings": post_path}
|
| 281 |
|
| 282 |
+
duckdb = _require_duckdb()
|
| 283 |
+
bm25_db = spill / "bm25_tf.duckdb"
|
| 284 |
+
if bm25_db.exists():
|
| 285 |
+
bm25_db.unlink()
|
| 286 |
+
conn = duckdb.connect(str(bm25_db))
|
|
|
|
|
|
|
|
|
|
| 287 |
conn.execute(
|
| 288 |
+
"CREATE TABLE tf (term VARCHAR NOT NULL, doc INTEGER NOT NULL, "
|
| 289 |
+
"ttf INTEGER NOT NULL, btf INTEGER NOT NULL)"
|
| 290 |
)
|
| 291 |
title_len = np.zeros(n_docs, dtype=np.int32)
|
| 292 |
body_len = np.zeros(n_docs, dtype=np.int32)
|
|
|
|
| 317 |
]
|
| 318 |
processed = 0
|
| 319 |
batch_rows: list[tuple] = []
|
|
|
|
| 320 |
for batch_tbl in pf.iter_batches(batch_size=batch, columns=cols):
|
| 321 |
d = batch_tbl.to_pydict()
|
| 322 |
m = len(d["document_index"])
|
|
|
|
| 360 |
}
|
| 361 |
)
|
| 362 |
if len(batch_rows) >= 20_000:
|
| 363 |
+
conn.executemany("INSERT INTO tf VALUES (?, ?, ?, ?)", batch_rows)
|
|
|
|
|
|
|
| 364 |
batch_rows.clear()
|
| 365 |
processed += m
|
| 366 |
if len(meta_buf) >= 20_000:
|
|
|
|
| 377 |
checkpoint(f"bm25_tf_tokenize", row=processed, every_n=20_000, log=log)
|
| 378 |
gc.collect()
|
| 379 |
if batch_rows:
|
| 380 |
+
conn.executemany("INSERT INTO tf VALUES (?, ?, ?, ?)", batch_rows)
|
| 381 |
batch_rows.clear()
|
| 382 |
if meta_buf:
|
| 383 |
dfm = pd.DataFrame(meta_buf)
|
|
|
|
| 388 |
dfm.to_parquet(meta_path, index=False)
|
| 389 |
del dfm
|
| 390 |
meta_buf.clear()
|
|
|
|
| 391 |
if log:
|
| 392 |
+
log("bm25 tf spilled to duckdb; writing documents")
|
| 393 |
|
| 394 |
doc_len = (title_len * TITLE_WEIGHT + body_len * BODY_WEIGHT).astype(np.float64)
|
| 395 |
avgdl = float(doc_len.mean()) if n_docs else 0.0
|
|
|
|
| 460 |
|
| 461 |
for term, doc, ttf, btf in conn.execute(
|
| 462 |
"SELECT term, doc, ttf, btf FROM tf ORDER BY term, doc"
|
| 463 |
+
).fetchall():
|
| 464 |
term = str(term)
|
| 465 |
if cur_term is None:
|
| 466 |
cur_term = term
|
|
|
|
| 513 |
"n_posting_rows": int(out_rows),
|
| 514 |
"n_postings": int(n_postings),
|
| 515 |
}
|
| 516 |
+
stats_json.write_text(json.dumps(stats, indent=2) + "\n", encoding="utf-8")
|
| 517 |
try:
|
| 518 |
+
bm25_db.unlink()
|
| 519 |
except Exception:
|
| 520 |
pass
|
| 521 |
if log:
|
|
|
|
| 523 |
return {"stats": stats, "documents": docs_path, "postings": post_path}
|
| 524 |
|
| 525 |
|
| 526 |
+
def should_use_spill(n_docs: int, threshold: int = DUCKDB_THRESHOLD) -> bool:
|
| 527 |
return n_docs >= threshold
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
def should_use_sqlite(n_docs: int, threshold: int = DUCKDB_THRESHOLD) -> bool:
|
| 531 |
+
"""Alias: large-corpus path is DuckDB/parquet, not SQLite."""
|
| 532 |
+
return should_use_spill(n_docs, threshold)
|
country_laws_ir/upload.py
CHANGED
|
@@ -1,24 +1,132 @@
|
|
| 1 |
-
"""
|
| 2 |
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 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 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Publish a local country-laws-ir release to the JusticeDAO Hugging Face org.
|
| 2 |
|
| 3 |
+
Reads stay anonymous (see ``auth.py``). Writes require an explicit ``--upload``
|
| 4 |
+
path, a ``justicedao/`` repo id, and ``HF_TOKEN``. Protected LCR repositories
|
| 5 |
+
are fail-closed via ``require_unprotected_or_runtime``.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
"""
|
| 7 |
|
| 8 |
from __future__ import annotations
|
| 9 |
|
| 10 |
+
import os
|
| 11 |
from pathlib import Path
|
| 12 |
from typing import Any
|
| 13 |
|
| 14 |
+
from . import TARGET_ORG
|
| 15 |
+
|
| 16 |
+
_OPERATOR_HINT = (
|
| 17 |
+
"Publish later with: hf upload-large-folder "
|
| 18 |
+
"{repo} {local_dir} --repo-type dataset --no-private --num-workers 8 "
|
| 19 |
+
'--exclude "**/__pycache__/**" --exclude "**/*.pyc"'
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class UploadError(RuntimeError):
|
| 24 |
+
"""Raised when a JusticeDAO upload cannot proceed."""
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _token_from_env() -> str:
|
| 28 |
+
for key in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"):
|
| 29 |
+
value = (os.environ.get(key) or "").strip()
|
| 30 |
+
if value:
|
| 31 |
+
return value
|
| 32 |
+
token_path = Path.home() / ".cache" / "huggingface" / "token"
|
| 33 |
+
if token_path.is_file():
|
| 34 |
+
try:
|
| 35 |
+
return token_path.read_text(encoding="utf-8").strip()
|
| 36 |
+
except OSError:
|
| 37 |
+
return ""
|
| 38 |
+
return ""
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def upload_release(
|
| 42 |
+
local_dir: Path,
|
| 43 |
+
repo_id: str,
|
| 44 |
+
*,
|
| 45 |
+
token: str | None = None,
|
| 46 |
+
commit_message: str | None = None,
|
| 47 |
+
create: bool = True,
|
| 48 |
+
) -> dict[str, Any]:
|
| 49 |
+
local_dir = Path(local_dir)
|
| 50 |
+
repo_id = str(repo_id or "").strip()
|
| 51 |
+
if not local_dir.is_dir():
|
| 52 |
+
raise UploadError(f"release directory does not exist: {local_dir}")
|
| 53 |
+
if not repo_id.startswith(f"{TARGET_ORG}/"):
|
| 54 |
+
raise UploadError(
|
| 55 |
+
f"country-laws-ir publishes only to {TARGET_ORG}/*; got {repo_id!r}"
|
| 56 |
+
)
|
| 57 |
+
if not (local_dir / "manifest.json").is_file():
|
| 58 |
+
raise UploadError(f"release is missing manifest.json: {local_dir}")
|
| 59 |
+
|
| 60 |
+
# Fail closed for LCR-protected repos without importing the full package
|
| 61 |
+
# (site-packages ipfs_datasets_py can be stale and break this thin packager).
|
| 62 |
+
_protected = {"justicedao/ipfs_state_laws", "justicedao/ipfs_federal_register"}
|
| 63 |
+
if repo_id in _protected:
|
| 64 |
+
raise UploadError(
|
| 65 |
+
f"{repo_id} is a protected JusticeDAO repository; "
|
| 66 |
+
"mutate it only through legal_corpora_publication_runtime"
|
| 67 |
+
)
|
| 68 |
+
try:
|
| 69 |
+
from ipfs_datasets_py.huggingface.protected_repo_guard import (
|
| 70 |
+
require_unprotected_or_runtime,
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
require_unprotected_or_runtime(repo_id, method="upload_folder")
|
| 74 |
+
except UploadError:
|
| 75 |
+
raise
|
| 76 |
+
except Exception:
|
| 77 |
+
pass
|
| 78 |
+
|
| 79 |
+
resolved = (token or "").strip() or _token_from_env()
|
| 80 |
+
if not resolved:
|
| 81 |
+
raise UploadError(
|
| 82 |
+
"HF_TOKEN is required for --upload. "
|
| 83 |
+
+ _OPERATOR_HINT.format(repo=repo_id, local_dir=local_dir)
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
from huggingface_hub import HfApi
|
| 87 |
+
|
| 88 |
+
api = HfApi(token=resolved)
|
| 89 |
+
if create:
|
| 90 |
+
api.create_repo(repo_id=repo_id, repo_type="dataset", exist_ok=True, private=False)
|
| 91 |
+
ignore = ["**/__pycache__/**", "**/*.pyc", "**/*.tmp", "**/*.tmp.npy"]
|
| 92 |
+
n_files = sum(1 for path in local_dir.rglob("*") if path.is_file())
|
| 93 |
+
nbytes = sum(path.stat().st_size for path in local_dir.rglob("*") if path.is_file())
|
| 94 |
+
use_large = n_files >= 80 or nbytes >= 80 * 1024 * 1024
|
| 95 |
+
if use_large and hasattr(api, "upload_large_folder"):
|
| 96 |
+
api.upload_large_folder(
|
| 97 |
+
folder_path=str(local_dir),
|
| 98 |
+
repo_id=repo_id,
|
| 99 |
+
repo_type="dataset",
|
| 100 |
+
ignore_patterns=ignore,
|
| 101 |
+
)
|
| 102 |
+
revision = ""
|
| 103 |
+
try:
|
| 104 |
+
from huggingface_hub import dataset_info as _dataset_info
|
| 105 |
|
| 106 |
+
pinned = _dataset_info(repo_id, token=resolved)
|
| 107 |
+
revision = str(getattr(pinned, "sha", "") or "")
|
| 108 |
+
except Exception:
|
| 109 |
+
revision = ""
|
| 110 |
+
return {
|
| 111 |
+
"url": f"https://huggingface.co/datasets/{repo_id}",
|
| 112 |
+
"repo_id": repo_id,
|
| 113 |
+
"revision": revision,
|
| 114 |
+
"local_dir": str(local_dir),
|
| 115 |
+
"method": "upload_large_folder",
|
| 116 |
+
}
|
| 117 |
+
info = api.upload_folder(
|
| 118 |
+
folder_path=str(local_dir),
|
| 119 |
+
repo_id=repo_id,
|
| 120 |
+
repo_type="dataset",
|
| 121 |
+
commit_message=commit_message
|
| 122 |
+
or f"Incremental country-laws-ir GraphRAG release for {repo_id}",
|
| 123 |
+
ignore_patterns=ignore,
|
| 124 |
)
|
| 125 |
+
revision = getattr(info, "oid", None) or getattr(info, "commit_id", None) or ""
|
| 126 |
+
return {
|
| 127 |
+
"url": f"https://huggingface.co/datasets/{repo_id}",
|
| 128 |
+
"repo_id": repo_id,
|
| 129 |
+
"revision": revision,
|
| 130 |
+
"local_dir": str(local_dir),
|
| 131 |
+
"method": "upload_folder",
|
| 132 |
+
}
|
country_laws_ir/vectors.py
CHANGED
|
@@ -52,7 +52,7 @@ def encode_corpus(
|
|
| 52 |
from .auth import configure_hf
|
| 53 |
|
| 54 |
configure_hf()
|
| 55 |
-
cache_root = _Path("/
|
| 56 |
os.environ.setdefault("HF_HOME", str(cache_root))
|
| 57 |
os.environ.setdefault("HF_HUB_DISABLE_IMPLICIT_TOKEN", "1")
|
| 58 |
os.environ.setdefault(
|
|
@@ -160,25 +160,29 @@ def _spherical_kmeans(x: np.ndarray, k: int, iters: int = 12, seed: int = 0) ->
|
|
| 160 |
|
| 161 |
|
| 162 |
def _recursive_clusters(x: np.ndarray, max_size: int = MAX_ROWS_PER_FILE) -> list[np.ndarray]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
n = len(x)
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
continue
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
return clusters
|
| 182 |
|
| 183 |
|
| 184 |
def layout_vectors(corpus: pd.DataFrame, embeddings: np.ndarray) -> dict[str, Any]:
|
|
@@ -333,3 +337,89 @@ def layout_stub_vectors(corpus: pd.DataFrame, reason: str) -> dict[str, Any]:
|
|
| 333 |
],
|
| 334 |
},
|
| 335 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
from .auth import configure_hf
|
| 53 |
|
| 54 |
configure_hf()
|
| 55 |
+
cache_root = _Path(os.environ.get("COUNTRY_LAWS_IR_ROOT", str(_Path.home() / ".ipfs_datasets" / "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(
|
|
|
|
| 160 |
|
| 161 |
|
| 162 |
def _recursive_clusters(x: np.ndarray, max_size: int = MAX_ROWS_PER_FILE) -> list[np.ndarray]:
|
| 163 |
+
"""Split vectors into shards of at most *max_size* without unbounded recursion.
|
| 164 |
+
|
| 165 |
+
Spherical k-means can fail to split (all points one label). In that case
|
| 166 |
+
fall back to an even index split so layout cannot recurse forever.
|
| 167 |
+
"""
|
| 168 |
n = len(x)
|
| 169 |
+
if n == 0:
|
| 170 |
+
return []
|
| 171 |
+
pending: list[np.ndarray] = [np.arange(n)]
|
| 172 |
+
clusters: list[np.ndarray] = []
|
| 173 |
+
while pending:
|
| 174 |
+
idx = pending.pop()
|
| 175 |
+
if len(idx) <= max_size:
|
| 176 |
+
clusters.append(idx)
|
| 177 |
continue
|
| 178 |
+
labels = _spherical_kmeans(x[idx], k=2)
|
| 179 |
+
parts = [idx[labels == lab] for lab in (0, 1)]
|
| 180 |
+
parts = [p for p in parts if len(p)]
|
| 181 |
+
if len(parts) < 2 or max(len(p) for p in parts) == len(idx):
|
| 182 |
+
mid = len(idx) // 2
|
| 183 |
+
parts = [idx[:mid], idx[mid:]]
|
| 184 |
+
pending.extend(parts)
|
| 185 |
+
return clusters or [np.arange(n)]
|
|
|
|
| 186 |
|
| 187 |
|
| 188 |
def layout_vectors(corpus: pd.DataFrame, embeddings: np.ndarray) -> dict[str, Any]:
|
|
|
|
| 337 |
],
|
| 338 |
},
|
| 339 |
}
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def assemble_embeddings(
|
| 343 |
+
corpus: pd.DataFrame,
|
| 344 |
+
prior_by_cid: dict[str, list[float]] | None = None,
|
| 345 |
+
*,
|
| 346 |
+
encode_missing: bool = True,
|
| 347 |
+
batch_size: int = 64,
|
| 348 |
+
device: str = "cpu",
|
| 349 |
+
checkpoint_path: str | None = None,
|
| 350 |
+
) -> tuple[np.ndarray, dict[str, Any]]:
|
| 351 |
+
"""Align a (n, 384) matrix to *corpus* row order, reusing unchanged CIDs.
|
| 352 |
+
|
| 353 |
+
Positional checkpoints are unsafe when scrapes append pages. Identity is
|
| 354 |
+
``entry_cid``. Missing CIDs are encoded only when ``encode_missing`` is true
|
| 355 |
+
and sentence-transformers is available.
|
| 356 |
+
"""
|
| 357 |
+
n = int(len(corpus))
|
| 358 |
+
out = np.zeros((n, DIMENSION), dtype=np.float32)
|
| 359 |
+
prior = prior_by_cid or {}
|
| 360 |
+
reused_idx: list[int] = []
|
| 361 |
+
missing_idx: list[int] = []
|
| 362 |
+
cids = corpus["entry_cid"].astype(str).tolist() if n else []
|
| 363 |
+
for i, cid in enumerate(cids):
|
| 364 |
+
vec = prior.get(cid)
|
| 365 |
+
if vec is None:
|
| 366 |
+
missing_idx.append(i)
|
| 367 |
+
continue
|
| 368 |
+
try:
|
| 369 |
+
arr = np.asarray(vec, dtype=np.float32).reshape(-1)
|
| 370 |
+
except Exception:
|
| 371 |
+
missing_idx.append(i)
|
| 372 |
+
continue
|
| 373 |
+
if arr.shape[0] != DIMENSION:
|
| 374 |
+
missing_idx.append(i)
|
| 375 |
+
continue
|
| 376 |
+
out[i] = arr
|
| 377 |
+
reused_idx.append(i)
|
| 378 |
+
|
| 379 |
+
report: dict[str, Any] = {
|
| 380 |
+
"n_docs": n,
|
| 381 |
+
"n_reused": len(reused_idx),
|
| 382 |
+
"n_encoded": 0,
|
| 383 |
+
"n_missing": len(missing_idx),
|
| 384 |
+
"model_name": MODEL_NAME,
|
| 385 |
+
"dimension": DIMENSION,
|
| 386 |
+
"status": "reused" if not missing_idx else "partial",
|
| 387 |
+
}
|
| 388 |
+
if not missing_idx:
|
| 389 |
+
report["status"] = "reused"
|
| 390 |
+
return _l2_normalize(out) if n else out, report
|
| 391 |
+
if not encode_missing:
|
| 392 |
+
report["status"] = "incomplete"
|
| 393 |
+
return out, report
|
| 394 |
+
if not embeddings_available():
|
| 395 |
+
report["status"] = "stub_missing_encoder"
|
| 396 |
+
report["reason"] = "sentence-transformers/torch unavailable"
|
| 397 |
+
return out, report
|
| 398 |
+
|
| 399 |
+
missing = corpus.iloc[missing_idx].reset_index(drop=True)
|
| 400 |
+
encoded = encode_corpus(
|
| 401 |
+
missing,
|
| 402 |
+
batch_size=batch_size,
|
| 403 |
+
device=device,
|
| 404 |
+
checkpoint_path=checkpoint_path,
|
| 405 |
+
)
|
| 406 |
+
for local_i, corpus_i in enumerate(missing_idx):
|
| 407 |
+
out[corpus_i] = encoded[local_i]
|
| 408 |
+
report["n_encoded"] = int(len(missing_idx))
|
| 409 |
+
report["n_missing"] = 0
|
| 410 |
+
report["status"] = "merged"
|
| 411 |
+
return _l2_normalize(out), report
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
def embeddings_by_cid(corpus: pd.DataFrame, matrix: np.ndarray) -> dict[str, list[float]]:
|
| 415 |
+
"""Project a row-aligned embedding matrix back to a CID map."""
|
| 416 |
+
out: dict[str, list[float]] = {}
|
| 417 |
+
if corpus is None or corpus.empty:
|
| 418 |
+
return out
|
| 419 |
+
x = np.asarray(matrix, dtype=np.float32)
|
| 420 |
+
cids = corpus["entry_cid"].astype(str).tolist()
|
| 421 |
+
for i, cid in enumerate(cids):
|
| 422 |
+
if i >= len(x):
|
| 423 |
+
break
|
| 424 |
+
out[cid] = x[i].astype(np.float32).tolist()
|
| 425 |
+
return out
|
data/bm25/documents/part-000000.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:294554df475057dfed6b86149ea892b17fb1c22699a94f3a51708f4f38cae438
|
| 3 |
+
size 515338
|
data/bm25/documents/part-000001.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:514461cb0e3acfbe7979265fd70be56d74dd4002e29f3e598a270b21a48a6b85
|
| 3 |
+
size 376787
|
data/bm25/postings/part-000000.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c45a5e312424a98df8a7c540900be908d170cd3a639f4182899b71265d20eecb
|
| 3 |
+
size 121424
|
data/corpus/part-000000.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a468393fe819e3eb672936989c670fdf53d7cc95ea2813c13e54a3d55539f87b
|
| 3 |
+
size 2182154
|
data/corpus/part-000001.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cf7eb157f3e815bca421ee5977ed814c305ec5eab641cff93037a0eccd5be4be
|
| 3 |
+
size 883744
|
data/graph/adjacency/in/part-000000.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:394b2df5a2470b13c74df83e46cbcfab37d2b434989efd1e166f7b9ae6a9de9e
|
| 3 |
+
size 518784
|
data/graph/adjacency/in/part-000001.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:88820f1c6924de8a604eda60c283e842cff8675881e484d7adc5229424ab35c8
|
| 3 |
+
size 533231
|
data/graph/adjacency/in/part-000002.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1322752bec7cba98b80d77109b5c2a70f60fb5a1fc686be668f25f1c443fac84
|
| 3 |
+
size 478023
|
data/graph/adjacency/in/part-000003.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a61299e363d10f7d7bea10020dfe28ed7ad41c31456b2b04c463ca4169eeb4f5
|
| 3 |
+
size 482166
|
data/graph/adjacency/in/part-000004.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:29c96c3e94055ad64d25c7a05e89720b7c4e33e9bb31e620b5e77685af9a975c
|
| 3 |
+
size 485307
|
data/graph/adjacency/in/part-000005.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9553a61e6e0e128e58cae8cada34847592e42f9e012651d4c58d12a783ff9b6c
|
| 3 |
+
size 395686
|
data/graph/adjacency/in/part-000006.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:70dca37fb2fa6fc0402370b6cd0fc232aed66f3429ad2d1abded9a342464990a
|
| 3 |
+
size 415646
|
data/graph/adjacency/out/part-000000.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:64976e58f205b5f1be4083439251e6fdd3540274bc3da39cab3e8142b012cf37
|
| 3 |
+
size 342228
|
data/graph/adjacency/out/part-000001.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b3b8acb06592daa9412ecbe250c0c86ff89b3ac250c490efc37bd2354fd4cb21
|
| 3 |
+
size 342371
|
data/graph/adjacency/out/part-000002.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d27eaf0434199ca99409d26dc1f14ae0102a724dc1797a0fa46a7373bc30e12c
|
| 3 |
+
size 342699
|
data/graph/adjacency/out/part-000003.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:aeeae8c9df77fb9a7172828edc2b079697b1450493cd48df20f22102df4e48de
|
| 3 |
+
size 342131
|
data/graph/adjacency/out/part-000004.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cf94d9abcfafa169e1f5925d205a2302f290d62b7825890ea91b1d755d8c8d04
|
| 3 |
+
size 343253
|
data/graph/adjacency/out/part-000005.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0b4328dddb91ae0242136d16db4ce48338c54aff81b0c604c4a064e5478f574b
|
| 3 |
+
size 342684
|
data/graph/adjacency/out/part-000006.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:840f10f7a48cee017040284f70020231c6840717de50da9c2edae50201b8566e
|
| 3 |
+
size 61281
|
data/graph/edges/part-000000.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:32ab186365708b90ff61ffa173aaaac85184d42f8514f48ebcf6c0e0be7c3b30
|
| 3 |
+
size 264562
|
data/graph/edges/part-000001.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bf316b04b8b922ee9f143cc766f66e6076fb495f60a400e0e847285614d28816
|
| 3 |
+
size 265032
|
data/graph/edges/part-000002.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:aef0aac061a4d85f7ed4ed99b1c695d76a3ac76d2a648b9a20cb60daba936b2f
|
| 3 |
+
size 265803
|
data/graph/edges/part-000003.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:94b042536fef2e395a7b43d492ee85041079a98b84116b9b90d04cecd50b8a5d
|
| 3 |
+
size 264851
|
data/graph/edges/part-000004.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:464f03c76ecb06b050e827421db8bf5c1936bcacb6a51bd798510c22da43cb11
|
| 3 |
+
size 264985
|
data/graph/edges/part-000005.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7643d06945a00aff2f7193deb398d67dd4c7a89d2112c8cd11642d7109bc08d3
|
| 3 |
+
size 266393
|
data/graph/edges/part-000006.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a4d0ea82d592d97f8668d4013bf8fe63472ad736cb8c77c1e70ccabc62830026
|
| 3 |
+
size 265910
|
data/graph/edges/part-000007.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d7850fd4aaf23d9f1d18a2cced497d1181c51b82aae326abd3266bd12e59d45d
|
| 3 |
+
size 264530
|
data/graph/edges/part-000008.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:070ae9d0cc103e57f64887863a806182ff495eaba236451361bd01cf41400f80
|
| 3 |
+
size 266023
|
data/graph/edges/part-000009.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:29360cc08242bdc38828f2454c9644197a43da7bad5c8c49eaaefc5b443c59b1
|
| 3 |
+
size 266323
|
data/graph/edges/part-000010.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5b061ef0caa60f59725d9bdacfc176b19923621c1562be74cbfd794d290f70e0
|
| 3 |
+
size 265788
|