Commit ·
0a50834
0
Parent(s):
ICJ Citation Graph release with Parquet and Docker runtime
Browse files- .env.example +17 -0
- .gitattributes +66 -0
- LICENSE +73 -0
- README.md +107 -0
- RUN_GRAPH.md +90 -0
- SHA256SUMS +62 -0
- compose.yaml +70 -0
- manifest.json +102 -0
- notebooks/dataset_demo.ipynb +191 -0
- runtime/.dockerignore +5 -0
- runtime/Dockerfile +7 -0
- runtime/Dockerfile.restore +5 -0
- runtime/graphkit/__init__.py +1 -0
- runtime/graphkit/__main__.py +63 -0
- runtime/graphkit/_api.py +58 -0
- runtime/graphkit/_graph.py +43 -0
- runtime/graphkit/_state.py +34 -0
- runtime/graphkit/_vectors.py +18 -0
- runtime/graphkit/config.py +12 -0
- runtime/graphkit/download.py +26 -0
- runtime/graphkit/embedding.py +39 -0
- runtime/graphkit/indexes.py +30 -0
- runtime/graphkit/parquet.py +40 -0
- runtime/graphkit/schema.py +12 -0
- runtime/requirements.txt +6 -0
- runtime/restore.sh +36 -0
- runtime/tests/test_vectors.py +79 -0
.env.example
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
NEO4J_PASSWORD=replace-with-a-strong-password
|
| 2 |
+
ICJ_DATA_DIR=./data
|
| 3 |
+
ICJ_REVISION=main
|
| 4 |
+
HF_TOKEN=
|
| 5 |
+
NEO4J_HTTP_PORT=7474
|
| 6 |
+
NEO4J_BOLT_PORT=7687
|
| 7 |
+
NEO4J_HEAP=2G
|
| 8 |
+
NEO4J_PAGECACHE=1G
|
| 9 |
+
|
| 10 |
+
# Optional OpenAI-compatible embedding API. Leave unset for Parquet import.
|
| 11 |
+
EMBEDDING_BASE_URL=https://openrouter.ai/api/v1
|
| 12 |
+
EMBEDDING_MODEL=qwen/qwen3-embedding-8b
|
| 13 |
+
EMBEDDING_API_KEY=
|
| 14 |
+
# 0 means use the provider's default dimension and validate its response.
|
| 15 |
+
EMBEDDING_DIMENSIONS=0
|
| 16 |
+
EMBEDDING_MAX_CHARS=8000
|
| 17 |
+
EMBEDDING_DOCUMENT_PREFIX=
|
.gitattributes
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 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
|
| 61 |
+
dataset/chunks.jsonl filter=lfs diff=lfs merge=lfs -text
|
| 62 |
+
neo4j.dump filter=lfs diff=lfs merge=lfs -text
|
| 63 |
+
dumps/icj-decisions.dump filter=lfs diff=lfs merge=lfs -text
|
| 64 |
+
dumps/icj-full.dump filter=lfs diff=lfs merge=lfs -text
|
| 65 |
+
dataset_layered/chunks.jsonl filter=lfs diff=lfs merge=lfs -text
|
| 66 |
+
docs/eda.pdf filter=lfs diff=lfs merge=lfs -text
|
LICENSE
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Scope of this snapshot
|
| 2 |
+
|
| 3 |
+
The source-specific terms below cover the original ICJ layers. This snapshot also includes UN resolutions, external-court material, and additional instruments. The dataset authors grant no new rights over that underlying material; consult each source's terms. The CC-BY-4.0 grant over this project's own contributions continues to apply.
|
| 4 |
+
|
| 5 |
+
# License and rights statement
|
| 6 |
+
|
| 7 |
+
This dataset carries material of mixed provenance, so it carries mixed terms. A single
|
| 8 |
+
blanket license would misstate the position, which is why the repository declares
|
| 9 |
+
`license: other` and defers to this file. The terms below apply per layer, and follow
|
| 10 |
+
the authorship of the underlying document.
|
| 11 |
+
|
| 12 |
+
## Summary
|
| 13 |
+
|
| 14 |
+
We grant a licence only over what we made. Everything else is either passed through from
|
| 15 |
+
upstream or carries a usage request, because we hold no rights to license it.
|
| 16 |
+
|
| 17 |
+
| Layer | Source | Status |
|
| 18 |
+
|---|---|---|
|
| 19 |
+
| everything we produced (parsing, chunking, embeddings, graph structure, tooling) | this project | **licensed CC-BY-4.0** |
|
| 20 |
+
| decision, where derived from CD-ICJ | Zenodo, DOI 10.5281/zenodo.3826444 | **CC0-1.0 passed through** from upstream |
|
| 21 |
+
| decision, where retrieved from icj-cij.org | ICJ | no licence granted; usage request below |
|
| 22 |
+
| oral (verbatim records) | ICJ Registry | no licence granted; usage request below |
|
| 23 |
+
| pleadings (party filings) | the parties, published by the ICJ | no licence granted; usage request below, and see the caveat |
|
| 24 |
+
|
| 25 |
+
**Usage request** for the material we did not create and cannot license: attribute the
|
| 26 |
+
ICJ and this dataset, and do not use it commercially. Those are the terms CC-BY-NC-4.0
|
| 27 |
+
expresses, and they are the reading the ICJ notice requires, but we state them as a
|
| 28 |
+
request rather than stamping a licence we are not in a position to grant. Treating this
|
| 29 |
+
as settled permission would be a mistake.
|
| 30 |
+
|
| 31 |
+
## Why the terms differ by layer
|
| 32 |
+
|
| 33 |
+
The rights position on the underlying documents is genuinely mixed, and we state it
|
| 34 |
+
rather than assert a blanket public-domain status.
|
| 35 |
+
|
| 36 |
+
The Rules of Court provide that pleadings and oral records are made accessible to the
|
| 37 |
+
public at or after the opening of oral proceedings (Rules of Court, Art. 53). That
|
| 38 |
+
provision governs access, not downstream reuse.
|
| 39 |
+
|
| 40 |
+
Separately, the ICJ asserts rights over its site and official publications: the notice
|
| 41 |
+
reserves all rights and states that content may not be reproduced or used for
|
| 42 |
+
commercial purposes. No ICJ or UN source addresses text and data mining or corpus
|
| 43 |
+
reuse, so there is no permission to point to and no prohibition specific to this use.
|
| 44 |
+
|
| 45 |
+
The government-edicts doctrine, which denies copyright in judicial texts, is keyed to
|
| 46 |
+
adjudicative authorship. It reaches what the Court writes. It does not squarely reach
|
| 47 |
+
what the parties write, which is why pleadings are treated separately here.
|
| 48 |
+
|
| 49 |
+
Our basis for release is the research and transformative-use rationale recognized for
|
| 50 |
+
legal-text corpora, together with the public-interest character of the material.
|
| 51 |
+
|
| 52 |
+
## The part that is not settled
|
| 53 |
+
|
| 54 |
+
The pleadings layer is the least certain of the three. Those documents are
|
| 55 |
+
party-authored, the government-edicts reasoning does not clearly cover them, and the
|
| 56 |
+
question has not been put to the ICJ Registry. The usage request above is the position
|
| 57 |
+
we apply pending that contact, not a determination that the parties or the Court have
|
| 58 |
+
licensed the material.
|
| 59 |
+
|
| 60 |
+
If you are a rights holder and object to any part of this release, contact us and we
|
| 61 |
+
will honor the request.
|
| 62 |
+
|
| 63 |
+
## What we do not claim
|
| 64 |
+
|
| 65 |
+
We claim no ownership of the underlying ICJ documents. The CC-BY-4.0 grant in the table
|
| 66 |
+
covers only the work this project added on top of them: the parsing and structure, the
|
| 67 |
+
chunking, the embeddings, the citation graph, and the tooling that produces all of it.
|
| 68 |
+
|
| 69 |
+
## Attribution
|
| 70 |
+
|
| 71 |
+
Underlying documents: International Court of Justice (icj-cij.org). The historical
|
| 72 |
+
decision corpus is derived from CD-ICJ by Sean Fobbe (Zenodo, DOI
|
| 73 |
+
10.5281/zenodo.3826444), released under CC0-1.0.
|
README.md
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: other
|
| 3 |
+
license_name: icj-mixed-per-layer
|
| 4 |
+
license_link: LICENSE
|
| 5 |
+
language:
|
| 6 |
+
- en
|
| 7 |
+
- fr
|
| 8 |
+
tags:
|
| 9 |
+
- legal
|
| 10 |
+
- international-law
|
| 11 |
+
- icj
|
| 12 |
+
- united-nations
|
| 13 |
+
- citation-graph
|
| 14 |
+
- embeddings
|
| 15 |
+
pretty_name: ICJ Citation Graph
|
| 16 |
+
size_categories:
|
| 17 |
+
- 1M<n<10M
|
| 18 |
+
configs:
|
| 19 |
+
- config_name: chunks
|
| 20 |
+
default: true
|
| 21 |
+
data_files: parquet/chunks-*.parquet
|
| 22 |
+
- config_name: documents
|
| 23 |
+
data_files: parquet/documents.parquet
|
| 24 |
+
- config_name: cases
|
| 25 |
+
data_files: parquet/cases.parquet
|
| 26 |
+
- config_name: provisions
|
| 27 |
+
data_files: parquet/provisions.parquet
|
| 28 |
+
- config_name: instruments
|
| 29 |
+
data_files: parquet/instruments.parquet
|
| 30 |
+
- config_name: resolutions
|
| 31 |
+
data_files: parquet/resolutions.parquet
|
| 32 |
+
- config_name: reschunks
|
| 33 |
+
data_files: parquet/reschunks-*.parquet
|
| 34 |
+
- config_name: document_resolution_edges
|
| 35 |
+
data_files: parquet/icj_resolution_edges.parquet
|
| 36 |
+
- config_name: resolution_edges
|
| 37 |
+
data_files: parquet/resolution_edges.parquet
|
| 38 |
+
---
|
| 39 |
+
|
| 40 |
+
# ICJ Citation Graph
|
| 41 |
+
|
| 42 |
+
The International Court of Justice (ICJ) collection provides structured text from decisions, written pleadings and oral records with citation links to cases and legal provisions. It also includes documents from other courts and a United Nations resolution graph containing resolution texts and citation links.
|
| 43 |
+
|
| 44 |
+
## Data
|
| 45 |
+
|
| 46 |
+
The counts below cover the records included in this release and do not represent the full holdings of each institution. The [manifest](manifest.json) records table counts and embedding coverage.
|
| 47 |
+
|
| 48 |
+
| Records | Count |
|
| 49 |
+
|---|---:|
|
| 50 |
+
| Cases, including external cases and citation targets | 571 |
|
| 51 |
+
| Documents | 6,901 |
|
| 52 |
+
| Document passages | 1,206,400 |
|
| 53 |
+
| Legal instruments / provisions | 370 / 12,375 |
|
| 54 |
+
| UN resolutions / resolution passages | 20,291 / 169,617 |
|
| 55 |
+
| Document-to-resolution citation links | 2,054 |
|
| 56 |
+
| Resolution-to-resolution citation links | 53,110 |
|
| 57 |
+
|
| 58 |
+
The documents comprise 6,396 ICJ records and 505 external-court records. Join documents to cases on `case_id` to filter by court. UN resolutions include 17,463 General Assembly and 2,828 Security Council records. `icj_resolution_edges` includes citations from external-court documents too.
|
| 59 |
+
|
| 60 |
+
## Files
|
| 61 |
+
|
| 62 |
+
Allow approximately **12.15 GB** for the download plus additional space for the restored database and indexes.
|
| 63 |
+
|
| 64 |
+
| Files | Contents |
|
| 65 |
+
|---|---|
|
| 66 |
+
| `dumps/neo4j.dump` | Complete Neo4j 5.26 snapshot without embeddings or vector indexes (approximately 0.84 GB) |
|
| 67 |
+
| `parquet/` | Text, metadata, selected citation relationships and stored embeddings |
|
| 68 |
+
| `compose.yaml`, `runtime/` | Graph restore, Parquet vector import and configurable embedding API client |
|
| 69 |
+
|
| 70 |
+
The dump contains all graph relationships including links to judges and countries. Parquet can be used independently of Neo4j and joined to graph records through application IDs because Neo4j internal IDs are regenerated during export.
|
| 71 |
+
|
| 72 |
+
## Get started
|
| 73 |
+
|
| 74 |
+
Install `datasets` and load a table:
|
| 75 |
+
|
| 76 |
+
```python
|
| 77 |
+
from datasets import load_dataset
|
| 78 |
+
|
| 79 |
+
documents = load_dataset(
|
| 80 |
+
"VISAI-AI/icj-citation-graph", "documents", split="train"
|
| 81 |
+
)
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
Authenticate with `hf auth login` if repository access requires it. Available table names appear in the dataset viewer above.
|
| 85 |
+
|
| 86 |
+
- [Notebook](notebooks/dataset_demo.ipynb): inspect tables, follow UN citations and search a passage sample.
|
| 87 |
+
- [Run the graph](RUN_GRAPH.md): start Neo4j with Docker Compose and choose how to add vectors. Import them from Parquet or generate them through a hosted or local OpenAI-compatible endpoint.
|
| 88 |
+
|
| 89 |
+
## Embeddings
|
| 90 |
+
|
| 91 |
+
Parquet includes 4,096-dimensional `Qwen3-Embedding-8B` vectors rounded to float16 precision and stored as float32 lists.
|
| 92 |
+
|
| 93 |
+
| Tables | Vector column | Availability |
|
| 94 |
+
|---|---|---|
|
| 95 |
+
| `chunks`, `reschunks`, `provisions` | `embedding` | Every row |
|
| 96 |
+
| `cases` | `name_embedding` | 427 of 571 rows |
|
| 97 |
+
| `resolutions` | `title_embedding` | 17,649 of 20,291 rows |
|
| 98 |
+
|
| 99 |
+
Missing vectors are stored as nulls and can be generated through a configured embedding endpoint. The runtime supports different endpoints and models and stores new embeddings in a separate property by default. Stored vectors can be imported without an API call, while new text queries require compatible model and preprocessing settings.
|
| 100 |
+
|
| 101 |
+
## Sources and limits
|
| 102 |
+
|
| 103 |
+
The ICJ collection combines [Sean Fobbe's CD-ICJ corpus](https://doi.org/10.5281/zenodo.3826444) with material retrieved from the Court's website. Added material retains source metadata where available. Consult [LICENSE](LICENSE) before reuse because terms vary by source.
|
| 104 |
+
|
| 105 |
+
Text recognition, paragraph boundaries and extracted citations may contain errors. Language labels may describe the source edition rather than each passage. Missing citation links do not establish the absence of a citation.
|
| 106 |
+
|
| 107 |
+
Use [SHA256SUMS](SHA256SUMS) to verify downloaded files.
|
RUN_GRAPH.md
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Run the ICJ graph
|
| 2 |
+
|
| 3 |
+
The dump contains the complete snapshot graph without embedding properties or vector indexes. Parquet contains the stored vectors, keyed by application IDs. Restore and query the graph without an embedding API, or import vectors from Parquet. Calling an embedding API is a separate, explicit command.
|
| 4 |
+
|
| 5 |
+
## Start Neo4j
|
| 6 |
+
|
| 7 |
+
Install Docker Engine with Docker Compose. Download `compose.yaml`, `.env.example`, `runtime/`, and this guide from the same dataset revision. Keep their directory layout.
|
| 8 |
+
|
| 9 |
+
```bash
|
| 10 |
+
cp .env.example .env
|
| 11 |
+
# Edit NEO4J_PASSWORD. For a private dataset, also set HF_TOKEN.
|
| 12 |
+
docker compose --profile tools run --build --rm fetch fetch
|
| 13 |
+
docker compose up --build -d --wait neo4j
|
| 14 |
+
docker compose --profile tools run --rm worker inspect
|
| 15 |
+
```
|
| 16 |
+
|
| 17 |
+
The fetch command pins one Hub commit per invocation and verifies downloaded files against its SHA256SUMS. Set `ICJ_REVISION` to a release commit to keep later downloads on the same snapshot. Dataset downloads go to `./data`; Neo4j and worker state use named Docker volumes. If you already downloaded the entire dataset, set `ICJ_DATA_DIR=.` instead and skip fetch.
|
| 18 |
+
|
| 19 |
+
Open http://localhost:7474 and log in as `neo4j` with your configured password. Both published ports bind to localhost. Use `NEO4J_HTTP_PORT` and `NEO4J_BOLT_PORT` for alternate ports. Allow approximately 10 GB of free disk and 4 GB of available RAM for the graph without vectors; full vectors and indexes need substantially more disk and memory.
|
| 20 |
+
|
| 21 |
+
Restore runs only for a new graph volume, verifies the dump checksum, and stages interrupted loads before moving them into place. It refuses to overwrite an unrelated database or switch an existing volume to another release. Use another Compose project name (`docker compose -p another-graph ...`) for a separate graph. `docker compose down` retains data; adding `-v` deletes its named volumes.
|
| 22 |
+
|
| 23 |
+
## Fill vectors from Parquet without an embedding API
|
| 24 |
+
|
| 25 |
+
```bash
|
| 26 |
+
docker compose --profile tools run --rm fetch fetch --vectors
|
| 27 |
+
docker compose --profile tools run --rm worker vectors --targets cases --limit 20
|
| 28 |
+
docker compose --profile tools run --rm worker indexes --targets cases
|
| 29 |
+
# Full import, when ready:
|
| 30 |
+
docker compose --profile tools run --rm worker vectors
|
| 31 |
+
# Build the full vector indexes separately; the chunk index is large:
|
| 32 |
+
docker compose --profile tools run --rm worker indexes
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
`--limit` is the maximum number of newly added vectors **per target in that invocation**. Re-running with a limit processes the next missing vectors. Omit it to process all. `--batch-size` controls working memory. Interrupted imports resume by skipping committed vectors; reruns may scan Parquet again. Keep the state volume and run one vector worker per graph. Existing vectors with different or unknown provenance are rejected rather than overwritten.
|
| 36 |
+
|
| 37 |
+
| Target | ID | Graph property | Available snapshot vectors |
|
| 38 |
+
|---|---|---|---:|
|
| 39 |
+
| chunks | `Chunk.id` | `embedding` | 1,206,400 |
|
| 40 |
+
| reschunks | `ResChunk.id` | `embedding` | 169,617 |
|
| 41 |
+
| provisions | `Provision.key` | `embedding` | 12,375 |
|
| 42 |
+
| cases | `Case.case_id` | `name_embedding` | 427 / 571 |
|
| 43 |
+
| resolutions | `Resolution.symbol` | `title_embedding` | 17,649 / 20,291 |
|
| 44 |
+
|
| 45 |
+
Vectors come from the stored Qwen3-Embedding-8B configuration, converted to float16 for publication and represented in Parquet's float32 list column. Missing case-name and resolution-title vectors are null, matching the source snapshot. IDs, not file positions or regenerated Neo4j internal IDs, determine where vectors are written. Imported vectors can reproduce the published quantized values, not bit-identical higher-precision source values.
|
| 46 |
+
|
| 47 |
+
## Use an embedding API
|
| 48 |
+
|
| 49 |
+
The client accepts an OpenAI-compatible embeddings endpoint with `data[].index` and `data[].embedding` responses. Set these in `.env`:
|
| 50 |
+
|
| 51 |
+
```dotenv
|
| 52 |
+
EMBEDDING_BASE_URL=https://openrouter.ai/api/v1
|
| 53 |
+
EMBEDDING_MODEL=qwen/qwen3-embedding-8b
|
| 54 |
+
EMBEDDING_API_KEY=your-key
|
| 55 |
+
EMBEDDING_DIMENSIONS=0
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
For a local server, use its API base, for example `http://host.docker.internal:8000/v1`, its model name, and an empty key if it does not require authentication. The URL may also be the complete `/embeddings` endpoint. Providers with a different request/response protocol require an adapter; native Ollama endpoints are not the same protocol, but its OpenAI-compatible endpoint can be used if supported by your installation.
|
| 59 |
+
|
| 60 |
+
```bash
|
| 61 |
+
# Small, paid API smoke test; no full-corpus API call happens automatically:
|
| 62 |
+
docker compose --profile tools run --rm worker embed --targets cases --limit 2
|
| 63 |
+
docker compose --profile tools run --rm worker indexes --targets cases --property api_embedding
|
| 64 |
+
# To process the remaining case names with the same configuration:
|
| 65 |
+
docker compose --profile tools run --rm worker embed --targets cases
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
API vectors default to `api_embedding`, leaving the published vectors in their original properties. Choose another `--property` for another model or preprocessing configuration. All graph targets are supported. Input text comes from chunk/provision text, case names, or resolution titles. By default, text is truncated to 8,000 characters and vectors are L2-normalized. Set `EMBEDDING_MAX_CHARS` and `EMBEDDING_DOCUMENT_PREFIX` for your provider/model. Query vectors must use that model's compatible query preprocessing. A matching model name across providers alone does not guarantee identical retrieval results.
|
| 69 |
+
|
| 70 |
+
With `EMBEDDING_DIMENSIONS=0`, the provider chooses its default. A positive value is sent as the API `dimensions` parameter and validated. Not every provider supports that parameter. Responses are reordered by `index` and checked for count, dimension, finite values and nonzero norms. Neo4j 5.26 vector indexes support the dimension range enforced by the index command (1 to 4096).
|
| 71 |
+
|
| 72 |
+
API batches are cached in the state volume before graph writes, so an interrupted graph write can reuse the response. Requests are retried for temporary network errors, rate limits and selected server errors. A network timeout can still leave uncertainty about whether a provider billed a request. There is no automatic full-corpus cost estimate; start with `--limit` and check your provider's usage. API keys are passed at runtime and must never be committed.
|
| 73 |
+
|
| 74 |
+
## Query an index
|
| 75 |
+
|
| 76 |
+
```cypher
|
| 77 |
+
MATCH (c:Case) WHERE c.name_embedding IS NOT NULL
|
| 78 |
+
WITH c LIMIT 1
|
| 79 |
+
CALL db.index.vector.queryNodes('case_name_embedding', 5, c.name_embedding)
|
| 80 |
+
YIELD node, score
|
| 81 |
+
RETURN node.case_id, node.name, score;
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
This uses a stored vector and requires no API. For API vectors, use the corresponding generated index name (for example `Case_api_embedding_vector`) and property. An index built after a limited import searches only nodes whose vectors have been filled.
|
| 85 |
+
|
| 86 |
+
## Run without Compose
|
| 87 |
+
|
| 88 |
+
Install `runtime/requirements.txt`, add `runtime` to `PYTHONPATH`, and run `python -m graphkit --help`. Set `NEO4J_URI`, `NEO4J_USERNAME`, `NEO4J_PASSWORD`, optionally `NEO4J_DATABASE`, and a writable `STATE_DIR`. `vectors --data-dir PATH` accepts a local dataset directory. The same code works against an existing compatible graph with matching application IDs; it does not create missing corpus nodes or relationships.
|
| 89 |
+
|
| 90 |
+
Tests: `PYTHONPATH=runtime python -m unittest discover -s runtime/tests -v`.
|
SHA256SUMS
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
04b28e7a3561963bdb40bbbe16169e62768b3565aa5b296a94157fb5886d1da6 .env.example
|
| 2 |
+
44b96bbe57991cbca3fe29b242e5d703f7c5b67407f2fdb0c3c85a8990800fb7 LICENSE
|
| 3 |
+
c54e9ff741fd2f4443fe7e87fc7c2ec0d243ddfe4dec2b2c734cfc13f9e28bb0 README.md
|
| 4 |
+
95ba07c344b7a1383f274437067c123271b9aee90edb2456083766e391ffef35 RUN_GRAPH.md
|
| 5 |
+
2f63963917dcddc9097d606fd3c65dbbdd5ca7906e2ebbf92c637908f2dff9f9 compose.yaml
|
| 6 |
+
3e9bf6811cd8f083c97c544c38dd595f4bc76791893742c21f70188aed2a1423 dumps/neo4j.dump
|
| 7 |
+
c8816448b6482593981128d2161121fbd0cc7f1e77ab218bf9315abcd9cd3511 manifest.json
|
| 8 |
+
05d6c4519dbfbfc8b073622fb7330c97d1f8f09b799de2e37e1f778363892a20 notebooks/dataset_demo.ipynb
|
| 9 |
+
72a980d5a2fecb6e64831ccb36c67eb57e3aff7b83bda67d0fcb664912ec38b1 parquet/cases.parquet
|
| 10 |
+
8f4cc0fb9c2815fe5020d1377dde13e0e492894ec559edf060d6f2fadfcafe47 parquet/chunks-000.parquet
|
| 11 |
+
7233ca06a6932bf170dffed5e690aebf87766207670e615d82024d3425c5815a parquet/chunks-001.parquet
|
| 12 |
+
d66a035bff42ee0c2d16c1c5ed05cb2cb9a6c67e40fc24ec4b0be4b4c7a8d595 parquet/chunks-002.parquet
|
| 13 |
+
5fb0f273c5c05441d46bcc20c16efd3c2fc1ed0fffcac1d72af872cfc65e87f4 parquet/chunks-003.parquet
|
| 14 |
+
4e357481146447cb509a0dd8a919da5145c05177ad55a8c20d785246effff41a parquet/chunks-004.parquet
|
| 15 |
+
2bb351ecdb6d57f0121ac2eb3f53d7bd99d4b6c6339e0dda6f938095c5a09c1d parquet/chunks-005.parquet
|
| 16 |
+
da851fbff9d27eca600c5436e3662b3053e13069bd92222e9368ca0f7d50b92a parquet/chunks-006.parquet
|
| 17 |
+
584026e3d54dd4a4e4589de7f217192907886f6336a77bec2e6adb5e90ace919 parquet/chunks-007.parquet
|
| 18 |
+
992e1adb9fd488e80272766c74078a336ad6477a9be55988c76d7fa4b7ad5b5a parquet/chunks-008.parquet
|
| 19 |
+
49d614939d333bec5c32fc2c822b3fb7c944d09f581d60aa99532971d428398b parquet/chunks-009.parquet
|
| 20 |
+
647188094a737a77487d16deac45ddd2c36aa0a26a82d2663ed6682b022570f4 parquet/chunks-010.parquet
|
| 21 |
+
b723c65d19abe244f0e765757e9913c02a59716f1afbc54890aa33bd09b81d50 parquet/chunks-011.parquet
|
| 22 |
+
b78f44ad8d17ff9bb3ecc2ab19fdbcdae9eecb3b7559af1c5d3b73f0448759fc parquet/chunks-012.parquet
|
| 23 |
+
cf467fafa16f2479be19e73db122a1abf6ed66d636cbc2406a87b609b4eed565 parquet/chunks-013.parquet
|
| 24 |
+
4fc14f622ed002d2faa80c7af7f16b4ff205e0a43de6c2b63db8369925023406 parquet/chunks-014.parquet
|
| 25 |
+
cf96e5007e3e8210f1e5f8c2143c37e00c52f84498797f9d85e3ee1e78b87dfe parquet/chunks-015.parquet
|
| 26 |
+
618df2078bd964a74d29129cfb25a3e6c97bb3de27e1634dd1af15f8ce6a052d parquet/chunks-016.parquet
|
| 27 |
+
ded026e2a4dc55039cc744a4a9d813beb5718b3099d1a602a161de425551a8c4 parquet/chunks-017.parquet
|
| 28 |
+
7f05d94d1d6def581a07775adc1f4e56bc6b15713784219f839b9bb8abc9014d parquet/chunks-018.parquet
|
| 29 |
+
254a15b8e5570109a3cfd2dc130cf9f863a1ea6bd25770226c3aa37fa9f75c78 parquet/chunks-019.parquet
|
| 30 |
+
1704f4518052e95b9d6fa1cde89ed87a2017320bde09823abcc365ae9798d0e1 parquet/chunks-020.parquet
|
| 31 |
+
fa0d33030eedd00b4975655c7b24a897d5d30d791b6f5b3a299df496ef59762a parquet/chunks-021.parquet
|
| 32 |
+
5fcb44e7c788434d31c5b3cf93a071834cbe8b038dfa1016fd8c88208b7e3397 parquet/chunks-022.parquet
|
| 33 |
+
47a1bde2dca8de8f2622465ff0540890bb1d1f80ba0943bbdf1c95e582df12bb parquet/chunks-023.parquet
|
| 34 |
+
a76b4a4ccff1a79f6564b086fc07a0996f9677a572640bf3551ec3b6958b1f65 parquet/chunks-024.parquet
|
| 35 |
+
00090dd350e038bfca517b7d26dd9f8fbb50375e44a1a7bdb8b85673f469d44a parquet/documents.parquet
|
| 36 |
+
9d6584b571aa6eac1aa28aea1614d8bbb397750bea3c97f7a211f311f7b2ee1f parquet/icj_resolution_edges.parquet
|
| 37 |
+
996e4947187118f0b6d125444b3be151501c5a331586efa563754a0b55663d4e parquet/instruments.parquet
|
| 38 |
+
0c0edae3d6d8328592f5d1779a21204f084ecf7cf276b3073a339f2f621da58c parquet/provisions.parquet
|
| 39 |
+
67938903202b71e2448060a805f90120087b8e0cf4292e690de127cc7fcd8706 parquet/reschunks-000.parquet
|
| 40 |
+
123c01fd83f82402f5af1f5ffcf119c89310cca9f08fd846689c92a1df2633a2 parquet/reschunks-001.parquet
|
| 41 |
+
cb6c4b01e6b7f330bc7ac491ad4f67c91268fbe9c04e44285cf4eb570c2d10a7 parquet/reschunks-002.parquet
|
| 42 |
+
6aa273cb19a2fa098bd64b4fd45b90fcb15362c206a538a76258134c76f32a4d parquet/reschunks-003.parquet
|
| 43 |
+
04b756d537e15cc76be1ce5e22937b1d0d74fdcfa5731276a912419aa5e80f0c parquet/resolution_edges.parquet
|
| 44 |
+
25b5e29025d14d3f4aa69dffc276a41d9a63f83572780d18a343ad7f1fb991b4 parquet/resolutions.parquet
|
| 45 |
+
30fa1b9869d7de5e882a730ba1782678dff2054d009e5be10af0c7519680d113 runtime/.dockerignore
|
| 46 |
+
2f9bf33221eb4a25af425afd5cd32d462a93d7c315ecd5b54f7e657773add195 runtime/Dockerfile
|
| 47 |
+
fec929057c54b6814068e3d7725bb2210daa4b54fc87227cf5be9fe29274d2ca runtime/Dockerfile.restore
|
| 48 |
+
01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b runtime/graphkit/__init__.py
|
| 49 |
+
eaeb0e315e7d85ceea92ca5318f716f8bd614712d09070a027598a9a903544e2 runtime/graphkit/__main__.py
|
| 50 |
+
375d73ac0f47d8826552dac13844cadb94885969cb6bf476ea668d5b73d5c090 runtime/graphkit/_api.py
|
| 51 |
+
8146caf5b83ff51a3cedd6ab6093ccac0bfeed400d925a52f23a0a8211ff7885 runtime/graphkit/_graph.py
|
| 52 |
+
af3558a2e7860f82f44b936a4e43340310e7aaa61f9e4862e09e614a6fd3b255 runtime/graphkit/_state.py
|
| 53 |
+
7d9a7807f2296a8e5679127ec35bf7b29e075bdfc13341e2e1f754e4eace4fb1 runtime/graphkit/_vectors.py
|
| 54 |
+
dee4029964a763f30cccf0187546e44766fb908fe672c322f5c11cfe1cb6e27c runtime/graphkit/config.py
|
| 55 |
+
c88daffbbf604990af09ac4ad9a39c5865f8382f3b3870683df402e470f4132c runtime/graphkit/download.py
|
| 56 |
+
f3d161f7d1c5e3a7796edabae4656bf80e82a6aaba45ace02e2594f8799d89c1 runtime/graphkit/embedding.py
|
| 57 |
+
78ef238db379c9b4a748a9cabc1d4e60b32324832c1fbbd387a44e275ef45631 runtime/graphkit/indexes.py
|
| 58 |
+
e5b003f6266f6213382a67ad36a4322d699f0a4d517dccb65e4355f23c0eeee8 runtime/graphkit/parquet.py
|
| 59 |
+
8955bea7cf181e5c28adc60cca22bc24d980bb0ff0ecc7f3d582eca39f44887e runtime/graphkit/schema.py
|
| 60 |
+
212f7fd5dec363178528bd3e46fcbef134bd748a7d0d8bc2a76948d168006f8f runtime/requirements.txt
|
| 61 |
+
d2be555434d088726d35dc1195c8a0f48e3a7f4ab732021fdf60bc2e9f9810f9 runtime/restore.sh
|
| 62 |
+
34a669738939e56ba87aebbfb4929d69243d2fe83164cc146c1acf617a5918ce runtime/tests/test_vectors.py
|
compose.yaml
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
fetch:
|
| 3 |
+
profiles: [tools]
|
| 4 |
+
build: ./runtime
|
| 5 |
+
command: [fetch]
|
| 6 |
+
environment:
|
| 7 |
+
HF_TOKEN: ${HF_TOKEN:-}
|
| 8 |
+
ICJ_REVISION: ${ICJ_REVISION:-main}
|
| 9 |
+
HF_HOME: /cache/huggingface
|
| 10 |
+
volumes:
|
| 11 |
+
- ${ICJ_DATA_DIR:-./data}:/dataset
|
| 12 |
+
- download-cache:/cache
|
| 13 |
+
|
| 14 |
+
restore:
|
| 15 |
+
build:
|
| 16 |
+
context: ./runtime
|
| 17 |
+
dockerfile: Dockerfile.restore
|
| 18 |
+
volumes:
|
| 19 |
+
- ${ICJ_DATA_DIR:-./data}:/dataset:ro
|
| 20 |
+
- graph-data:/data
|
| 21 |
+
restart: "no"
|
| 22 |
+
|
| 23 |
+
neo4j:
|
| 24 |
+
image: neo4j:5.26
|
| 25 |
+
depends_on:
|
| 26 |
+
restore:
|
| 27 |
+
condition: service_completed_successfully
|
| 28 |
+
environment:
|
| 29 |
+
NEO4J_AUTH: neo4j/${NEO4J_PASSWORD:?Set NEO4J_PASSWORD in .env}
|
| 30 |
+
NEO4J_server_memory_heap_max__size: ${NEO4J_HEAP:-2G}
|
| 31 |
+
NEO4J_server_memory_pagecache_size: ${NEO4J_PAGECACHE:-1G}
|
| 32 |
+
ports:
|
| 33 |
+
- "127.0.0.1:${NEO4J_HTTP_PORT:-7474}:7474"
|
| 34 |
+
- "127.0.0.1:${NEO4J_BOLT_PORT:-7687}:7687"
|
| 35 |
+
volumes:
|
| 36 |
+
- graph-data:/data
|
| 37 |
+
healthcheck:
|
| 38 |
+
test: [CMD-SHELL, 'cypher-shell -u neo4j -p "$${NEO4J_AUTH#neo4j/}" "RETURN 1" >/dev/null 2>&1']
|
| 39 |
+
interval: 10s
|
| 40 |
+
timeout: 10s
|
| 41 |
+
retries: 30
|
| 42 |
+
start_period: 20s
|
| 43 |
+
|
| 44 |
+
worker:
|
| 45 |
+
profiles: [tools]
|
| 46 |
+
build: ./runtime
|
| 47 |
+
depends_on:
|
| 48 |
+
neo4j:
|
| 49 |
+
condition: service_healthy
|
| 50 |
+
environment:
|
| 51 |
+
NEO4J_URI: bolt://neo4j:7687
|
| 52 |
+
NEO4J_USERNAME: neo4j
|
| 53 |
+
NEO4J_PASSWORD: ${NEO4J_PASSWORD:?Set NEO4J_PASSWORD in .env}
|
| 54 |
+
EMBEDDING_BASE_URL: ${EMBEDDING_BASE_URL:-}
|
| 55 |
+
EMBEDDING_API_KEY: ${EMBEDDING_API_KEY:-}
|
| 56 |
+
EMBEDDING_MODEL: ${EMBEDDING_MODEL:-}
|
| 57 |
+
EMBEDDING_DIMENSIONS: ${EMBEDDING_DIMENSIONS:-0}
|
| 58 |
+
EMBEDDING_MAX_CHARS: ${EMBEDDING_MAX_CHARS:-8000}
|
| 59 |
+
EMBEDDING_DOCUMENT_PREFIX: ${EMBEDDING_DOCUMENT_PREFIX:-}
|
| 60 |
+
STATE_DIR: /state
|
| 61 |
+
extra_hosts:
|
| 62 |
+
- host.docker.internal:host-gateway
|
| 63 |
+
volumes:
|
| 64 |
+
- ${ICJ_DATA_DIR:-./data}:/dataset:ro
|
| 65 |
+
- vector-state:/state
|
| 66 |
+
|
| 67 |
+
volumes:
|
| 68 |
+
graph-data:
|
| 69 |
+
vector-state:
|
| 70 |
+
download-cache:
|
manifest.json
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema_version": 3,
|
| 3 |
+
"source_id": "release-20260926T052243Z",
|
| 4 |
+
"counts": {
|
| 5 |
+
"cases": 571,
|
| 6 |
+
"documents": 6901,
|
| 7 |
+
"instruments": 370,
|
| 8 |
+
"provisions": 12375,
|
| 9 |
+
"resolutions": 20291,
|
| 10 |
+
"icj_resolution_edges": 2054,
|
| 11 |
+
"resolution_edges": 53110,
|
| 12 |
+
"reschunks": 169617,
|
| 13 |
+
"chunks": 1206400
|
| 14 |
+
},
|
| 15 |
+
"case_metadata_snapshot": "2026-07-14",
|
| 16 |
+
"embedding": {
|
| 17 |
+
"model": "Qwen3-Embedding-8B",
|
| 18 |
+
"dimension": 4096,
|
| 19 |
+
"dtype": "float16",
|
| 20 |
+
"tables": [
|
| 21 |
+
"chunks",
|
| 22 |
+
"reschunks",
|
| 23 |
+
"provisions",
|
| 24 |
+
"cases",
|
| 25 |
+
"resolutions"
|
| 26 |
+
],
|
| 27 |
+
"columns": {
|
| 28 |
+
"chunks": "embedding",
|
| 29 |
+
"reschunks": "embedding",
|
| 30 |
+
"provisions": "embedding",
|
| 31 |
+
"cases": "name_embedding",
|
| 32 |
+
"resolutions": "title_embedding"
|
| 33 |
+
},
|
| 34 |
+
"available_counts": {
|
| 35 |
+
"chunks": 1206400,
|
| 36 |
+
"reschunks": 169617,
|
| 37 |
+
"provisions": 12375,
|
| 38 |
+
"cases": 427,
|
| 39 |
+
"resolutions": 17649
|
| 40 |
+
}
|
| 41 |
+
},
|
| 42 |
+
"files": [
|
| 43 |
+
"dumps/neo4j.dump",
|
| 44 |
+
"parquet/cases.parquet",
|
| 45 |
+
"parquet/chunks-000.parquet",
|
| 46 |
+
"parquet/chunks-001.parquet",
|
| 47 |
+
"parquet/chunks-002.parquet",
|
| 48 |
+
"parquet/chunks-003.parquet",
|
| 49 |
+
"parquet/chunks-004.parquet",
|
| 50 |
+
"parquet/chunks-005.parquet",
|
| 51 |
+
"parquet/chunks-006.parquet",
|
| 52 |
+
"parquet/chunks-007.parquet",
|
| 53 |
+
"parquet/chunks-008.parquet",
|
| 54 |
+
"parquet/chunks-009.parquet",
|
| 55 |
+
"parquet/chunks-010.parquet",
|
| 56 |
+
"parquet/chunks-011.parquet",
|
| 57 |
+
"parquet/chunks-012.parquet",
|
| 58 |
+
"parquet/chunks-013.parquet",
|
| 59 |
+
"parquet/chunks-014.parquet",
|
| 60 |
+
"parquet/chunks-015.parquet",
|
| 61 |
+
"parquet/chunks-016.parquet",
|
| 62 |
+
"parquet/chunks-017.parquet",
|
| 63 |
+
"parquet/chunks-018.parquet",
|
| 64 |
+
"parquet/chunks-019.parquet",
|
| 65 |
+
"parquet/chunks-020.parquet",
|
| 66 |
+
"parquet/chunks-021.parquet",
|
| 67 |
+
"parquet/chunks-022.parquet",
|
| 68 |
+
"parquet/chunks-023.parquet",
|
| 69 |
+
"parquet/chunks-024.parquet",
|
| 70 |
+
"parquet/documents.parquet",
|
| 71 |
+
"parquet/icj_resolution_edges.parquet",
|
| 72 |
+
"parquet/instruments.parquet",
|
| 73 |
+
"parquet/provisions.parquet",
|
| 74 |
+
"parquet/reschunks-000.parquet",
|
| 75 |
+
"parquet/reschunks-001.parquet",
|
| 76 |
+
"parquet/reschunks-002.parquet",
|
| 77 |
+
"parquet/reschunks-003.parquet",
|
| 78 |
+
"parquet/resolution_edges.parquet",
|
| 79 |
+
"parquet/resolutions.parquet"
|
| 80 |
+
],
|
| 81 |
+
"row_order": {
|
| 82 |
+
"chunks": [
|
| 83 |
+
"document_id",
|
| 84 |
+
"seq",
|
| 85 |
+
"id"
|
| 86 |
+
],
|
| 87 |
+
"reschunks": [
|
| 88 |
+
"resolution_symbol",
|
| 89 |
+
"seq",
|
| 90 |
+
"id"
|
| 91 |
+
]
|
| 92 |
+
},
|
| 93 |
+
"formats": [
|
| 94 |
+
"neo4j-5.26-dump",
|
| 95 |
+
"parquet"
|
| 96 |
+
],
|
| 97 |
+
"dump": {
|
| 98 |
+
"vectors": false,
|
| 99 |
+
"vector_indexes": false,
|
| 100 |
+
"internal_ids_regenerated": true
|
| 101 |
+
}
|
| 102 |
+
}
|
notebooks/dataset_demo.ipynb
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"# ICJ Citation Graph: inspect data and run the graph\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"The release contains a complete Neo4j graph without vectors and Parquet tables with stored vectors. These examples inspect the tables, follow UN citations and search a bounded passage sample.\n",
|
| 10 |
+
"\n",
|
| 11 |
+
"Install `numpy`, `pandas`, `pyarrow` and `huggingface_hub`. Set `ICJ_DATASET_ROOT` to a complete local release directory to avoid downloads. Otherwise files are downloaded from one pinned Hugging Face commit. For a private repository, authenticate with `hf auth login` or set `HF_TOKEN` outside the notebook. Keep credentials out of saved cells and outputs.\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"Executable cells do not call an embedding API. Docker and optional API commands appear at the end as instructions to run explicitly.\n"
|
| 14 |
+
],
|
| 15 |
+
"id": "walkthrough-0"
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"source": [
|
| 21 |
+
"import json, os\n",
|
| 22 |
+
"from pathlib import Path\n",
|
| 23 |
+
"import numpy as np\n",
|
| 24 |
+
"import pandas as pd\n",
|
| 25 |
+
"import pyarrow.parquet as pq\n",
|
| 26 |
+
"from huggingface_hub import HfApi, hf_hub_download\n",
|
| 27 |
+
"\n",
|
| 28 |
+
"REPO = \"VISAI-AI/icj-citation-graph\"\n",
|
| 29 |
+
"ROOT = Path(os.environ[\"ICJ_DATASET_ROOT\"]).expanduser().resolve() if os.environ.get(\"ICJ_DATASET_ROOT\") else None\n",
|
| 30 |
+
"REVISION = None if ROOT else HfApi().dataset_info(REPO, revision=os.environ.get(\"ICJ_REVISION\", \"main\")).sha\n",
|
| 31 |
+
"\n",
|
| 32 |
+
"def grab(name):\n",
|
| 33 |
+
" if ROOT:\n",
|
| 34 |
+
" local = ROOT / name\n",
|
| 35 |
+
" if not local.is_file():\n",
|
| 36 |
+
" raise FileNotFoundError(f\"Missing local release file: {local}\")\n",
|
| 37 |
+
" return local\n",
|
| 38 |
+
" return Path(hf_hub_download(REPO, name, repo_type=\"dataset\", revision=REVISION))\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"print(\"Local directory:\" if ROOT else \"Hub commit:\", ROOT or REVISION)\n",
|
| 41 |
+
"manifest = json.loads(grab(\"manifest.json\").read_text())\n",
|
| 42 |
+
"assert manifest[\"schema_version\"] == 3\n",
|
| 43 |
+
"print(manifest[\"source_id\"], manifest[\"counts\"])\n"
|
| 44 |
+
],
|
| 45 |
+
"outputs": [],
|
| 46 |
+
"execution_count": null,
|
| 47 |
+
"id": "walkthrough-1"
|
| 48 |
+
},
|
| 49 |
+
{
|
| 50 |
+
"cell_type": "code",
|
| 51 |
+
"metadata": {},
|
| 52 |
+
"source": [
|
| 53 |
+
"cases = pd.read_parquet(grab(\"parquet/cases.parquet\"))\n",
|
| 54 |
+
"documents = pd.read_parquet(grab(\"parquet/documents.parquet\"))\n",
|
| 55 |
+
"assert len(cases) == manifest[\"counts\"][\"cases\"]\n",
|
| 56 |
+
"assert len(documents) == manifest[\"counts\"][\"documents\"]\n",
|
| 57 |
+
"print(documents[[\"id\", \"case_id\"]].merge(cases[[\"case_id\", \"court\"]], on=\"case_id\")[\"court\"].value_counts())\n",
|
| 58 |
+
"print(documents[\"layer\"].value_counts(dropna=False))\n"
|
| 59 |
+
],
|
| 60 |
+
"outputs": [],
|
| 61 |
+
"execution_count": null,
|
| 62 |
+
"id": "walkthrough-2"
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "markdown",
|
| 66 |
+
"metadata": {},
|
| 67 |
+
"source": [
|
| 68 |
+
"Follow document-to-resolution and resolution-to-resolution edges. The historical filename icj_resolution_edges also includes external-court documents."
|
| 69 |
+
],
|
| 70 |
+
"id": "walkthrough-3"
|
| 71 |
+
},
|
| 72 |
+
{
|
| 73 |
+
"cell_type": "code",
|
| 74 |
+
"metadata": {},
|
| 75 |
+
"source": [
|
| 76 |
+
"document_edges = pd.read_parquet(grab(\"parquet/icj_resolution_edges.parquet\"))\n",
|
| 77 |
+
"resolution_edges = pd.read_parquet(grab(\"parquet/resolution_edges.parquet\"))\n",
|
| 78 |
+
"assert len(document_edges) == manifest[\"counts\"][\"icj_resolution_edges\"]\n",
|
| 79 |
+
"assert len(resolution_edges) == manifest[\"counts\"][\"resolution_edges\"]\n",
|
| 80 |
+
"print(document_edges.head().to_string(index=False))\n",
|
| 81 |
+
"print(resolution_edges.head().to_string(index=False))\n"
|
| 82 |
+
],
|
| 83 |
+
"outputs": [],
|
| 84 |
+
"execution_count": null,
|
| 85 |
+
"id": "walkthrough-4"
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"cell_type": "markdown",
|
| 89 |
+
"metadata": {},
|
| 90 |
+
"source": [
|
| 91 |
+
"Read the first 2,048 UN passages and their inline vectors from one shard. This bounded example uses a stored vector as the query. New text queries require the same embedding model and preprocessing as the corpus."
|
| 92 |
+
],
|
| 93 |
+
"id": "walkthrough-5"
|
| 94 |
+
},
|
| 95 |
+
{
|
| 96 |
+
"cell_type": "code",
|
| 97 |
+
"metadata": {},
|
| 98 |
+
"source": [
|
| 99 |
+
"batch = next(pq.ParquetFile(grab(\"parquet/reschunks-000.parquet\")).iter_batches(\n",
|
| 100 |
+
" batch_size=2048, columns=[\"id\", \"resolution_symbol\", \"text\", \"embedding\"]\n",
|
| 101 |
+
"))\n",
|
| 102 |
+
"rows = batch.to_pylist()\n",
|
| 103 |
+
"vectors = np.asarray([row[\"embedding\"] for row in rows], dtype=np.float32)\n",
|
| 104 |
+
"assert vectors.shape == (len(rows), manifest[\"embedding\"][\"dimension\"])\n",
|
| 105 |
+
"assert np.isfinite(vectors).all()\n",
|
| 106 |
+
"assert np.all(np.linalg.norm(vectors, axis=1) > 0)\n",
|
| 107 |
+
"print(rows[0][\"resolution_symbol\"], rows[0][\"text\"][:400])\n",
|
| 108 |
+
"query = vectors[0]\n",
|
| 109 |
+
"scores = vectors @ query / (np.linalg.norm(vectors, axis=1) * np.linalg.norm(query))\n",
|
| 110 |
+
"for index in np.argsort(-scores)[:5]:\n",
|
| 111 |
+
" print(rows[index][\"id\"], float(scores[index]), rows[index][\"text\"][:160])\n"
|
| 112 |
+
],
|
| 113 |
+
"outputs": [],
|
| 114 |
+
"execution_count": null,
|
| 115 |
+
"id": "walkthrough-6"
|
| 116 |
+
},
|
| 117 |
+
{
|
| 118 |
+
"cell_type": "markdown",
|
| 119 |
+
"metadata": {},
|
| 120 |
+
"source": [
|
| 121 |
+
"## Name and title vector coverage\n",
|
| 122 |
+
"\n",
|
| 123 |
+
"Null name/title vectors preserve gaps in the source snapshot. The counts below are checked against the manifest. Exported vectors have float16 precision represented in Parquet float32 lists.\n"
|
| 124 |
+
],
|
| 125 |
+
"id": "icj-demo-07"
|
| 126 |
+
},
|
| 127 |
+
{
|
| 128 |
+
"cell_type": "code",
|
| 129 |
+
"execution_count": null,
|
| 130 |
+
"metadata": {},
|
| 131 |
+
"outputs": [],
|
| 132 |
+
"source": [
|
| 133 |
+
"resolutions = pd.read_parquet(grab(\"parquet/resolutions.parquet\"))\n",
|
| 134 |
+
"assert len(resolutions) == manifest[\"counts\"][\"resolutions\"]\n",
|
| 135 |
+
"coverage = []\n",
|
| 136 |
+
"for name, table, column in [(\"cases\", cases, \"name_embedding\"), (\"resolutions\", resolutions, \"title_embedding\")]:\n",
|
| 137 |
+
" available = int(table[column].notna().sum())\n",
|
| 138 |
+
" assert available == manifest[\"embedding\"][\"available_counts\"][name]\n",
|
| 139 |
+
" coverage.append({\"table\": name, \"records\": len(table), \"vectors\": available, \"missing\": len(table) - available})\n",
|
| 140 |
+
"print(pd.DataFrame(coverage).to_string(index=False))\n"
|
| 141 |
+
],
|
| 142 |
+
"id": "icj-demo-08"
|
| 143 |
+
},
|
| 144 |
+
{
|
| 145 |
+
"cell_type": "markdown",
|
| 146 |
+
"metadata": {},
|
| 147 |
+
"source": [
|
| 148 |
+
"## Restore Neo4j and import stored vectors\n",
|
| 149 |
+
"\n",
|
| 150 |
+
"Download `compose.yaml`, `.env.example` and `runtime/` from the same revision. Run these commands in that directory in a terminal. After copying `.env.example`, set `NEO4J_PASSWORD` and set `ICJ_REVISION` to the Hub commit printed above. With a complete local release, set `ICJ_DATA_DIR` to its absolute path and skip fetch.\n",
|
| 151 |
+
"\n",
|
| 152 |
+
"```bash\n",
|
| 153 |
+
"cp .env.example .env\n",
|
| 154 |
+
"# Edit .env before starting the services.\n",
|
| 155 |
+
"docker compose --profile tools run --build --rm fetch fetch --vectors\n",
|
| 156 |
+
"docker compose up --build -d --wait neo4j\n",
|
| 157 |
+
"docker compose --profile tools run --rm worker inspect\n",
|
| 158 |
+
"docker compose --profile tools run --rm worker vectors --targets cases --limit 20\n",
|
| 159 |
+
"docker compose --profile tools run --rm worker indexes --targets cases\n",
|
| 160 |
+
"```\n",
|
| 161 |
+
"\n",
|
| 162 |
+
"Import matches application IDs. The limit adds at most 20 new case-name vectors; repeating it processes the next missing records. Omit the limit to import all available vectors for the selected targets. `docker compose down` retains database and worker-state volumes. See [RUN_GRAPH.md](../RUN_GRAPH.md) for resource requirements and recovery behaviour.\n",
|
| 163 |
+
"\n",
|
| 164 |
+
"## Generate embeddings through a configured endpoint\n",
|
| 165 |
+
"\n",
|
| 166 |
+
"Set `EMBEDDING_BASE_URL`, `EMBEDDING_MODEL` and, if required, `EMBEDDING_API_KEY` in `.env`. OpenRouter uses `https://openrouter.ai/api/v1`; a local server can expose an OpenAI-compatible endpoint. Configure dimensions and text preprocessing for the selected model. Hosted requests may incur charges.\n",
|
| 167 |
+
"\n",
|
| 168 |
+
"```bash\n",
|
| 169 |
+
"docker compose --profile tools run --rm worker embed --targets cases --limit 2\n",
|
| 170 |
+
"docker compose --profile tools run --rm worker indexes --targets cases --property api_embedding\n",
|
| 171 |
+
"```\n",
|
| 172 |
+
"\n",
|
| 173 |
+
"Generated vectors use `api_embedding` by default. Use a different property when changing the model or preprocessing. New text queries require compatible query embeddings.\n"
|
| 174 |
+
],
|
| 175 |
+
"id": "icj-demo-09"
|
| 176 |
+
}
|
| 177 |
+
],
|
| 178 |
+
"metadata": {
|
| 179 |
+
"kernelspec": {
|
| 180 |
+
"display_name": "Python 3",
|
| 181 |
+
"language": "python",
|
| 182 |
+
"name": "python3"
|
| 183 |
+
},
|
| 184 |
+
"language_info": {
|
| 185 |
+
"name": "python",
|
| 186 |
+
"version": "3"
|
| 187 |
+
}
|
| 188 |
+
},
|
| 189 |
+
"nbformat": 4,
|
| 190 |
+
"nbformat_minor": 5
|
| 191 |
+
}
|
runtime/.dockerignore
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*
|
| 2 |
+
!requirements.txt
|
| 3 |
+
!graphkit/
|
| 4 |
+
!graphkit/*.py
|
| 5 |
+
!restore.sh
|
runtime/Dockerfile
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.13-slim
|
| 2 |
+
WORKDIR /app
|
| 3 |
+
COPY requirements.txt .
|
| 4 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 5 |
+
COPY graphkit ./graphkit
|
| 6 |
+
ENTRYPOINT ["python", "-u", "-m", "graphkit"]
|
| 7 |
+
CMD ["--help"]
|
runtime/Dockerfile.restore
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM neo4j:5.26
|
| 2 |
+
USER root
|
| 3 |
+
COPY restore.sh /restore.sh
|
| 4 |
+
RUN chmod 755 /restore.sh
|
| 5 |
+
ENTRYPOINT ["/restore.sh"]
|
runtime/graphkit/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
runtime/graphkit/__main__.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
from ._graph import Graph
|
| 6 |
+
from ._state import locked_state
|
| 7 |
+
from .config import TARGETS
|
| 8 |
+
from .download import fetch
|
| 9 |
+
from .embedding import embed_graph
|
| 10 |
+
from .indexes import create_indexes, inspect_graph
|
| 11 |
+
from .parquet import load_vectors
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def positive(value):
|
| 15 |
+
value = int(value)
|
| 16 |
+
if value < 1:
|
| 17 |
+
raise argparse.ArgumentTypeError('must be positive')
|
| 18 |
+
return value
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def main():
|
| 22 |
+
parser = argparse.ArgumentParser(description='Restore vectors and manage the ICJ graph. API calls are explicit.')
|
| 23 |
+
commands = parser.add_subparsers(dest='command', required=True)
|
| 24 |
+
download = commands.add_parser('fetch')
|
| 25 |
+
download.add_argument('--data-dir', default='/dataset')
|
| 26 |
+
download.add_argument('--revision', default=os.getenv('ICJ_REVISION', 'main'))
|
| 27 |
+
download.add_argument('--vectors', action='store_true')
|
| 28 |
+
commands.add_parser('inspect')
|
| 29 |
+
for name in ['vectors', 'embed', 'indexes']:
|
| 30 |
+
child = commands.add_parser(name)
|
| 31 |
+
child.add_argument('--targets', nargs='+', choices=list(TARGETS), default=list(TARGETS))
|
| 32 |
+
if name == 'indexes':
|
| 33 |
+
child.add_argument('--property')
|
| 34 |
+
child.add_argument('--timeout', type=positive, default=3600)
|
| 35 |
+
else:
|
| 36 |
+
child.add_argument('--batch-size', type=positive, default=64)
|
| 37 |
+
child.add_argument('--limit', type=positive, help='Maximum newly added vectors per target in this invocation; omit to process all.')
|
| 38 |
+
if name == 'vectors':
|
| 39 |
+
child.add_argument('--data-dir', default='/dataset')
|
| 40 |
+
else:
|
| 41 |
+
child.add_argument('--property', default='api_embedding')
|
| 42 |
+
args = parser.parse_args()
|
| 43 |
+
if args.command == 'fetch':
|
| 44 |
+
fetch(args.data_dir, args.revision, args.vectors)
|
| 45 |
+
return
|
| 46 |
+
graph = Graph()
|
| 47 |
+
try:
|
| 48 |
+
if args.command == 'inspect':
|
| 49 |
+
print(json.dumps(inspect_graph(graph), indent=2))
|
| 50 |
+
return
|
| 51 |
+
with locked_state(os.getenv('STATE_DIR', '/state')) as cache:
|
| 52 |
+
if args.command == 'vectors':
|
| 53 |
+
load_vectors(graph, args.targets, args.data_dir, args.batch_size, args.limit)
|
| 54 |
+
elif args.command == 'embed':
|
| 55 |
+
embed_graph(graph, args.targets, cache, args.property, args.batch_size, args.limit)
|
| 56 |
+
else:
|
| 57 |
+
create_indexes(graph, args.targets, args.property, args.timeout)
|
| 58 |
+
finally:
|
| 59 |
+
graph.close()
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
if __name__ == '__main__':
|
| 63 |
+
main()
|
runtime/graphkit/_api.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import time
|
| 3 |
+
from urllib.parse import urlsplit
|
| 4 |
+
|
| 5 |
+
import requests
|
| 6 |
+
|
| 7 |
+
from ._vectors import validate_vectors
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def api_settings():
|
| 11 |
+
endpoint = os.getenv('EMBEDDING_BASE_URL', '').rstrip('/')
|
| 12 |
+
model = os.getenv('EMBEDDING_MODEL', '')
|
| 13 |
+
if not endpoint or not model:
|
| 14 |
+
raise ValueError('Set EMBEDDING_BASE_URL and EMBEDDING_MODEL before calling the API.')
|
| 15 |
+
if not endpoint.endswith('/embeddings'):
|
| 16 |
+
endpoint += '/embeddings'
|
| 17 |
+
parsed = urlsplit(endpoint)
|
| 18 |
+
if parsed.scheme not in {'http', 'https'} or not parsed.hostname or parsed.username or parsed.password:
|
| 19 |
+
raise ValueError('Use an HTTP(S) endpoint without credentials in the URL.')
|
| 20 |
+
dimension = int(os.getenv('EMBEDDING_DIMENSIONS', '0'))
|
| 21 |
+
max_chars = int(os.getenv('EMBEDDING_MAX_CHARS', '8000'))
|
| 22 |
+
if dimension < 0 or max_chars < 1:
|
| 23 |
+
raise ValueError('Dimensions must be nonnegative and max chars positive.')
|
| 24 |
+
return {'endpoint': endpoint, 'model': model, 'dimensions': dimension, 'max_chars': max_chars,
|
| 25 |
+
'prefix': os.getenv('EMBEDDING_DOCUMENT_PREFIX', ''), 'normalize': True}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def response_vectors(payload, count, dimension):
|
| 29 |
+
items = payload.get('data')
|
| 30 |
+
if not isinstance(items, list) or len(items) != count:
|
| 31 |
+
raise ValueError('Embedding response count does not match the request.')
|
| 32 |
+
indexes = [item.get('index') for item in items]
|
| 33 |
+
if any(type(index) is not int for index in indexes) or sorted(indexes) != list(range(count)):
|
| 34 |
+
raise ValueError('Embedding response indexes are missing, duplicated or out of range.')
|
| 35 |
+
ordered = sorted(items, key=lambda item: item['index'])
|
| 36 |
+
return validate_vectors([item['embedding'] for item in ordered], dimension, normalize=True)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def embed(settings, texts):
|
| 40 |
+
payload = {'model': settings['model'], 'input': [settings['prefix'] + text[:settings['max_chars']] for text in texts], 'encoding_format': 'float'}
|
| 41 |
+
if settings['dimensions']:
|
| 42 |
+
payload['dimensions'] = settings['dimensions']
|
| 43 |
+
headers = {'Content-Type': 'application/json'}
|
| 44 |
+
if os.getenv('EMBEDDING_API_KEY'):
|
| 45 |
+
headers['Authorization'] = 'Bearer ' + os.environ['EMBEDDING_API_KEY']
|
| 46 |
+
for attempt in range(5):
|
| 47 |
+
try:
|
| 48 |
+
response = requests.post(settings['endpoint'], json=payload, headers=headers, timeout=(15, 120))
|
| 49 |
+
except (requests.ConnectionError, requests.Timeout):
|
| 50 |
+
if attempt == 4:
|
| 51 |
+
raise RuntimeError('Embedding endpoint connection failed after five attempts.') from None
|
| 52 |
+
else:
|
| 53 |
+
if response.status_code == 200:
|
| 54 |
+
return response_vectors(response.json(), len(texts), settings['dimensions'])
|
| 55 |
+
if response.status_code not in {408, 429, 500, 502, 503, 504} or attempt == 4:
|
| 56 |
+
raise RuntimeError(f'Embedding endpoint returned HTTP {response.status_code}; check model, credentials and limits.')
|
| 57 |
+
time.sleep(min(2 ** attempt, 16))
|
| 58 |
+
raise RuntimeError('Embedding retries exhausted.')
|
runtime/graphkit/_graph.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
|
| 4 |
+
from neo4j import GraphDatabase
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def identifier(value):
|
| 8 |
+
if not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*', value):
|
| 9 |
+
raise ValueError('Invalid Cypher identifier: ' + value)
|
| 10 |
+
return '`' + value + '`'
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class Graph:
|
| 14 |
+
def __init__(self):
|
| 15 |
+
self.driver = GraphDatabase.driver(os.getenv('NEO4J_URI', 'bolt://neo4j:7687'), auth=(os.getenv('NEO4J_USERNAME', 'neo4j'), os.environ['NEO4J_PASSWORD']), notifications_min_severity='OFF')
|
| 16 |
+
self.database = os.getenv('NEO4J_DATABASE', 'neo4j')
|
| 17 |
+
|
| 18 |
+
def run(self, query, **params):
|
| 19 |
+
with self.driver.session(database=self.database) as session:
|
| 20 |
+
return [dict(record) for record in session.run(query, **params)]
|
| 21 |
+
|
| 22 |
+
def check_source(self, target, prop, source):
|
| 23 |
+
p = identifier(prop)
|
| 24 |
+
marker = identifier(prop + '__source')
|
| 25 |
+
mismatch = self.run(f'MATCH (n:{target.label}) WHERE n.{p} IS NOT NULL AND (n.{marker} IS NULL OR n.{marker} <> $source) RETURN count(n) AS n', source=source)[0]['n']
|
| 26 |
+
if mismatch:
|
| 27 |
+
raise ValueError(f'{mismatch} existing vectors have different or unknown provenance. Use a different --property or a fresh graph.')
|
| 28 |
+
|
| 29 |
+
def missing(self, target, ids, prop):
|
| 30 |
+
rows = self.run(f'UNWIND $ids AS key OPTIONAL MATCH (n:{target.label} {{{target.key}:key}}) RETURN key,n IS NOT NULL AS found,n.{identifier(prop)} IS NULL AS missing', ids=ids)
|
| 31 |
+
if len(rows) != len(ids) or not all(row['found'] for row in rows):
|
| 32 |
+
raise ValueError('Parquet keys do not match this graph snapshot.')
|
| 33 |
+
return {row['key'] for row in rows if row['missing']}
|
| 34 |
+
|
| 35 |
+
def write(self, target, prop, source, rows):
|
| 36 |
+
if not rows:
|
| 37 |
+
return
|
| 38 |
+
result = self.run(f'UNWIND $rows AS row MATCH (n:{target.label} {{{target.key}:row.key}}) WHERE n.{identifier(prop)} IS NULL SET n.{identifier(prop)}=row.vector,n.{identifier(prop + "__source")}=$source RETURN count(n) AS n', rows=rows, source=source)
|
| 39 |
+
if result[0]['n'] != len(rows):
|
| 40 |
+
raise RuntimeError('Graph changed during writing; stop concurrent vector writers and retry.')
|
| 41 |
+
|
| 42 |
+
def close(self):
|
| 43 |
+
self.driver.close()
|
runtime/graphkit/_state.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import fcntl
|
| 2 |
+
import hashlib
|
| 3 |
+
import json
|
| 4 |
+
import sqlite3
|
| 5 |
+
from contextlib import contextmanager
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def fingerprint(value):
|
| 10 |
+
return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@contextmanager
|
| 14 |
+
def locked_state(directory):
|
| 15 |
+
directory = Path(directory)
|
| 16 |
+
directory.mkdir(parents=True, exist_ok=True)
|
| 17 |
+
with (directory / 'worker.lock').open('a') as lock:
|
| 18 |
+
try:
|
| 19 |
+
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
| 20 |
+
except BlockingIOError:
|
| 21 |
+
raise RuntimeError('Another vector worker is using this state volume.') from None
|
| 22 |
+
with sqlite3.connect(directory / 'cache.sqlite') as db:
|
| 23 |
+
db.execute('CREATE TABLE IF NOT EXISTS vectors (key TEXT PRIMARY KEY, value TEXT NOT NULL)')
|
| 24 |
+
yield db
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def cached_vectors(db, key, produce):
|
| 28 |
+
row = db.execute('SELECT value FROM vectors WHERE key=?', (key,)).fetchone()
|
| 29 |
+
if row:
|
| 30 |
+
return json.loads(row[0])
|
| 31 |
+
vectors = produce()
|
| 32 |
+
db.execute('INSERT INTO vectors VALUES (?,?)', (key, json.dumps(vectors)))
|
| 33 |
+
db.commit()
|
| 34 |
+
return vectors
|
runtime/graphkit/_vectors.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def validate_vectors(values, dimension=None, normalize=False):
|
| 5 |
+
try:
|
| 6 |
+
array = np.asarray(values, dtype=np.float32)
|
| 7 |
+
except (TypeError, ValueError) as exc:
|
| 8 |
+
raise ValueError('Embedding response is not a rectangular numeric matrix.') from exc
|
| 9 |
+
if array.ndim != 2 or array.shape[0] == 0 or array.shape[1] == 0:
|
| 10 |
+
raise ValueError('Embeddings must be a nonempty matrix.')
|
| 11 |
+
if dimension and array.shape[1] != dimension:
|
| 12 |
+
raise ValueError(f'Embedding dimension {array.shape[1]} does not match {dimension}.')
|
| 13 |
+
norms = np.linalg.norm(array, axis=1)
|
| 14 |
+
if not np.isfinite(array).all() or not np.isfinite(norms).all() or np.any(norms == 0):
|
| 15 |
+
raise ValueError('Embeddings contain non-finite values or zero vectors.')
|
| 16 |
+
if normalize:
|
| 17 |
+
array = array / norms[:, None]
|
| 18 |
+
return array.tolist()
|
runtime/graphkit/config.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .schema import Target
|
| 2 |
+
|
| 3 |
+
TARGETS = {
|
| 4 |
+
'chunks': Target('Chunk', 'id', 'text', 'embedding', 'embedding', 'chunks-*.parquet', 'chunk_embedding'),
|
| 5 |
+
'reschunks': Target('ResChunk', 'id', 'text', 'embedding', 'embedding', 'reschunks-*.parquet', 'res_chunk_embedding'),
|
| 6 |
+
'provisions': Target('Provision', 'key', 'text', 'embedding', 'embedding', 'provisions.parquet', 'provision_embedding'),
|
| 7 |
+
'cases': Target('Case', 'case_id', 'name', 'name_embedding', 'name_embedding', 'cases.parquet', 'case_name_embedding'),
|
| 8 |
+
'resolutions': Target('Resolution', 'symbol', 'title', 'title_embedding', 'title_embedding', 'resolutions.parquet', 'resolution_embedding'),
|
| 9 |
+
}
|
| 10 |
+
REPO = 'VISAI-AI/icj-citation-graph'
|
| 11 |
+
PRETRAINED_MODEL = 'qwen/qwen3-embedding-8b'
|
| 12 |
+
PRETRAINED_DIMENSION = 4096
|
runtime/graphkit/download.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import hashlib
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
from huggingface_hub import HfApi, hf_hub_download
|
| 5 |
+
|
| 6 |
+
from .config import REPO
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def fetch(directory, revision, vectors):
|
| 10 |
+
root = Path(directory)
|
| 11 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 12 |
+
commit = HfApi().dataset_info(REPO, revision=revision).sha
|
| 13 |
+
sums = Path(hf_hub_download(REPO, 'SHA256SUMS', repo_type='dataset', revision=commit, local_dir=root))
|
| 14 |
+
hashes = dict(line.split(' ', 1)[::-1] for line in sums.read_text().splitlines())
|
| 15 |
+
selected = [name for name in hashes if name in {'manifest.json', 'dumps/neo4j.dump'} or (vectors and name.startswith('parquet/'))]
|
| 16 |
+
for name in selected:
|
| 17 |
+
relative = Path(name)
|
| 18 |
+
if relative.is_absolute() or '..' in relative.parts:
|
| 19 |
+
raise ValueError('Unsafe checksum path.')
|
| 20 |
+
path = Path(hf_hub_download(REPO, name, repo_type='dataset', revision=commit, local_dir=root))
|
| 21 |
+
with path.open('rb') as handle:
|
| 22 |
+
actual = hashlib.file_digest(handle, 'sha256').hexdigest()
|
| 23 |
+
if actual != hashes[name]:
|
| 24 |
+
raise ValueError('Checksum mismatch: ' + name)
|
| 25 |
+
print('Verified', name, flush=True)
|
| 26 |
+
print('Downloaded revision:', commit, flush=True)
|
runtime/graphkit/embedding.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
|
| 3 |
+
from ._api import api_settings, embed
|
| 4 |
+
from ._graph import identifier
|
| 5 |
+
from ._state import cached_vectors, fingerprint
|
| 6 |
+
from ._vectors import validate_vectors
|
| 7 |
+
from .config import TARGETS
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def embed_graph(graph, targets, cache, prop, batch_size, limit):
|
| 11 |
+
settings = api_settings()
|
| 12 |
+
source = fingerprint(settings)
|
| 13 |
+
counts = {}
|
| 14 |
+
for name in targets:
|
| 15 |
+
target = TARGETS[name]
|
| 16 |
+
if prop in {target.key, target.text, target.property}:
|
| 17 |
+
raise ValueError('API embeddings require a separate property, for example api_embedding.')
|
| 18 |
+
graph.check_source(target, prop, source)
|
| 19 |
+
dimension = settings['dimensions'] or None
|
| 20 |
+
existing = graph.run(f'MATCH (n:{target.label}) WHERE n.{identifier(prop)} IS NOT NULL RETURN DISTINCT size(n.{identifier(prop)}) AS dim')
|
| 21 |
+
if existing:
|
| 22 |
+
if len(existing) != 1 or (dimension and existing[0]['dim'] != dimension):
|
| 23 |
+
raise ValueError('Existing vector dimensions are inconsistent with configuration.')
|
| 24 |
+
dimension = existing[0]['dim']
|
| 25 |
+
written = 0
|
| 26 |
+
while not limit or written < limit:
|
| 27 |
+
size = min(batch_size, limit - written) if limit else batch_size
|
| 28 |
+
rows = graph.run(f'MATCH (n:{target.label}) WHERE n.{identifier(prop)} IS NULL AND n.{target.text} IS NOT NULL AND trim(n.{target.text}) <> "" RETURN n.{target.key} AS key,n.{target.text} AS text ORDER BY key LIMIT $size', size=size)
|
| 29 |
+
if not rows:
|
| 30 |
+
break
|
| 31 |
+
key = fingerprint({'source': source, 'target': name, 'rows': rows})
|
| 32 |
+
vectors = cached_vectors(cache, key, lambda: embed(settings, [row['text'] for row in rows]))
|
| 33 |
+
vectors = validate_vectors(vectors, dimension)
|
| 34 |
+
dimension = len(vectors[0])
|
| 35 |
+
graph.write(target, prop, source, [{'key': row['key'], 'vector': vector} for row, vector in zip(rows, vectors)])
|
| 36 |
+
written += len(rows)
|
| 37 |
+
print(json.dumps({'target': name, 'vectors_added': written, 'dimension': dimension}), flush=True)
|
| 38 |
+
counts[name] = written
|
| 39 |
+
return counts
|
runtime/graphkit/indexes.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ._graph import identifier
|
| 2 |
+
from .config import TARGETS
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def create_indexes(graph, targets, prop, timeout):
|
| 6 |
+
for name in targets:
|
| 7 |
+
target = TARGETS[name]
|
| 8 |
+
field = prop or target.property
|
| 9 |
+
index = f'{target.label}_{field}_vector' if prop else target.index
|
| 10 |
+
dims = graph.run(f'MATCH (n:{target.label}) WHERE n.{identifier(field)} IS NOT NULL RETURN DISTINCT size(n.{identifier(field)}) AS dim')
|
| 11 |
+
if len(dims) != 1 or not 1 <= dims[0]['dim'] <= 4096:
|
| 12 |
+
raise ValueError(f'{name}: requires nonempty vectors with one dimension in 1..4096.')
|
| 13 |
+
existing = graph.run('SHOW INDEXES YIELD name,type,labelsOrTypes,properties,options WHERE name=$name RETURN type,labelsOrTypes,properties,options', name=index)
|
| 14 |
+
if existing:
|
| 15 |
+
row = existing[0]
|
| 16 |
+
if (row['type'], row['labelsOrTypes'], row['properties']) != ('VECTOR', [target.label], [field]) or row['options']['indexConfig'].get('vector.dimensions') != dims[0]['dim']:
|
| 17 |
+
raise ValueError('Existing index conflicts with requested vectors: ' + index)
|
| 18 |
+
else:
|
| 19 |
+
graph.run(f'CREATE VECTOR INDEX {identifier(index)} FOR (n:{target.label}) ON (n.{identifier(field)}) OPTIONS {{indexConfig: {{`vector.dimensions`: $dim, `vector.similarity_function`: "cosine"}}}}', dim=dims[0]['dim'])
|
| 20 |
+
graph.run('CALL db.awaitIndex($name,$timeout)', name=index, timeout=timeout)
|
| 21 |
+
print('Index ready:', index, flush=True)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def inspect_graph(graph):
|
| 25 |
+
return {
|
| 26 |
+
'nodes': graph.run('MATCH (n) UNWIND labels(n) AS label RETURN label,count(*) AS count ORDER BY label'),
|
| 27 |
+
'relationships': graph.run('MATCH ()-[r]->() RETURN type(r) AS type,count(*) AS count ORDER BY type'),
|
| 28 |
+
'vectors': {name: graph.run(f'MATCH (n:{target.label}) RETURN count(n.{target.property}) AS count')[0]['count'] for name, target in TARGETS.items()},
|
| 29 |
+
'indexes': graph.run('SHOW INDEXES YIELD name,type,state RETURN name,type,state'),
|
| 30 |
+
}
|
runtime/graphkit/parquet.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
import pyarrow.parquet as pq
|
| 5 |
+
|
| 6 |
+
from ._state import fingerprint
|
| 7 |
+
from ._vectors import validate_vectors
|
| 8 |
+
from .config import PRETRAINED_DIMENSION, PRETRAINED_MODEL, TARGETS
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def load_vectors(graph, targets, directory, batch_size, limit):
|
| 12 |
+
root = Path(directory)
|
| 13 |
+
manifest = json.loads((root / 'manifest.json').read_text())
|
| 14 |
+
source = fingerprint({'release': manifest['source_id'], 'model': PRETRAINED_MODEL, 'dimension': PRETRAINED_DIMENSION, 'storage': 'float16'})
|
| 15 |
+
counts = {}
|
| 16 |
+
for name in targets:
|
| 17 |
+
target = TARGETS[name]
|
| 18 |
+
graph.check_source(target, target.property, source)
|
| 19 |
+
paths = sorted((root / 'parquet').glob(target.files))
|
| 20 |
+
if not paths:
|
| 21 |
+
raise FileNotFoundError(target.files)
|
| 22 |
+
written = 0
|
| 23 |
+
for path in paths:
|
| 24 |
+
for batch in pq.ParquetFile(path).iter_batches(batch_size=batch_size, columns=[target.key, target.column]):
|
| 25 |
+
items = [row for row in batch.to_pylist() if row[target.column] is not None]
|
| 26 |
+
missing = graph.missing(target, [row[target.key] for row in items], target.property)
|
| 27 |
+
pending = [row for row in items if row[target.key] in missing]
|
| 28 |
+
if limit:
|
| 29 |
+
pending = pending[:limit - written]
|
| 30 |
+
if pending:
|
| 31 |
+
vectors = validate_vectors([row[target.column] for row in pending], PRETRAINED_DIMENSION)
|
| 32 |
+
graph.write(target, target.property, source, [{'key': row[target.key], 'vector': vector} for row, vector in zip(pending, vectors)])
|
| 33 |
+
written += len(pending)
|
| 34 |
+
if limit and written >= limit:
|
| 35 |
+
break
|
| 36 |
+
if limit and written >= limit:
|
| 37 |
+
break
|
| 38 |
+
counts[name] = written
|
| 39 |
+
print(json.dumps({'target': name, 'vectors_added': written}), flush=True)
|
| 40 |
+
return counts
|
runtime/graphkit/schema.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
@dataclass(frozen=True)
|
| 5 |
+
class Target:
|
| 6 |
+
label: str
|
| 7 |
+
key: str
|
| 8 |
+
text: str
|
| 9 |
+
property: str
|
| 10 |
+
column: str
|
| 11 |
+
files: str
|
| 12 |
+
index: str
|
runtime/requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
neo4j==6.2.0
|
| 2 |
+
neo4j-rust-ext==6.2.0.0
|
| 3 |
+
numpy==2.4.3
|
| 4 |
+
pyarrow==25.0.1
|
| 5 |
+
requests==2.32.5
|
| 6 |
+
huggingface_hub==1.23.0
|
runtime/restore.sh
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/sh
|
| 2 |
+
set -eu
|
| 3 |
+
dump=/dataset/dumps/neo4j.dump
|
| 4 |
+
test -f "$dump" || { echo 'Download the dataset first; dumps/neo4j.dump is missing.' >&2; exit 1; }
|
| 5 |
+
expected=$(awk '$2 == "dumps/neo4j.dump" {print $1}' /dataset/SHA256SUMS)
|
| 6 |
+
test -n "$expected" || { echo 'Dump checksum is missing.' >&2; exit 1; }
|
| 7 |
+
actual=$(sha256sum "$dump" | cut -d ' ' -f 1)
|
| 8 |
+
test "$actual" = "$expected" || { echo 'Dump checksum mismatch.' >&2; exit 1; }
|
| 9 |
+
if test -f /data/.icj-restored; then
|
| 10 |
+
test "$(cat /data/.icj-restored)" = "$expected" || { echo 'This volume belongs to a different release. Use a new Compose project/volume.' >&2; exit 1; }
|
| 11 |
+
echo 'Graph already restored.'
|
| 12 |
+
exit 0
|
| 13 |
+
fi
|
| 14 |
+
if test -f /data/.icj-restoring; then
|
| 15 |
+
test "$(cat /data/.icj-restoring)" = "$expected" || { echo 'Interrupted restore belongs to another release.' >&2; exit 1; }
|
| 16 |
+
else
|
| 17 |
+
test ! -d /data/databases/neo4j || { echo 'Existing unrecognized database; refusing to replace it.' >&2; exit 1; }
|
| 18 |
+
printf '%s\n' "$expected" > /data/.icj-restoring
|
| 19 |
+
fi
|
| 20 |
+
if test ! -f /data/.icj-loaded; then
|
| 21 |
+
mkdir -p /data/.icj-stage
|
| 22 |
+
printf 'server.directories.data=/data/.icj-stage\nserver.directories.transaction.logs.root=/data/.icj-stage/transactions\n' > /tmp/restore.conf
|
| 23 |
+
neo4j-admin database load neo4j --from-path=/dataset/dumps --overwrite-destination=true --additional-config=/tmp/restore.conf
|
| 24 |
+
touch /data/.icj-loaded
|
| 25 |
+
fi
|
| 26 |
+
mkdir -p /data/databases /data/transactions
|
| 27 |
+
for section in databases transactions; do
|
| 28 |
+
if test -d "/data/.icj-stage/$section/neo4j"; then
|
| 29 |
+
test ! -d "/data/$section/neo4j" || { echo 'Conflicting restore directories.' >&2; exit 1; }
|
| 30 |
+
mv "/data/.icj-stage/$section/neo4j" "/data/$section/neo4j"
|
| 31 |
+
fi
|
| 32 |
+
done
|
| 33 |
+
test -f /data/databases/neo4j/neostore
|
| 34 |
+
chown -R neo4j:neo4j /data
|
| 35 |
+
mv /data/.icj-restoring /data/.icj-restored
|
| 36 |
+
echo 'Graph restored and checksum verified.'
|
runtime/tests/test_vectors.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import tempfile
|
| 4 |
+
import unittest
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from unittest.mock import patch
|
| 7 |
+
|
| 8 |
+
import pyarrow as pa
|
| 9 |
+
import pyarrow.parquet as pq
|
| 10 |
+
|
| 11 |
+
from graphkit._api import api_settings, response_vectors
|
| 12 |
+
from graphkit._graph import identifier
|
| 13 |
+
from graphkit._state import cached_vectors, locked_state
|
| 14 |
+
from graphkit.parquet import load_vectors
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class VectorTests(unittest.TestCase):
|
| 18 |
+
def test_reordered_api_response(self):
|
| 19 |
+
rows = {'data': [{'index': 1, 'embedding': [0, 2]}, {'index': 0, 'embedding': [3, 0]}]}
|
| 20 |
+
self.assertEqual(response_vectors(rows, 2, 2), [[1, 0], [0, 1]])
|
| 21 |
+
|
| 22 |
+
def test_bad_responses_are_rejected(self):
|
| 23 |
+
cases = [
|
| 24 |
+
({'data': [{'index': 0, 'embedding': [1, 0]}]}, 2, 2),
|
| 25 |
+
({'data': [{'index': 0, 'embedding': [0, 0]}]}, 1, 2),
|
| 26 |
+
({'data': [{'index': 0, 'embedding': [float('nan'), 1]}]}, 1, 2),
|
| 27 |
+
({'data': [{'index': 0, 'embedding': [1, 1]}]}, 1, 3),
|
| 28 |
+
({'data': [{'index': 1, 'embedding': [1, 0]}]}, 1, 2),
|
| 29 |
+
({'data': [{'index': 0, 'embedding': [1, 0]}, {'index': 0, 'embedding': [0, 1]}]}, 2, 2),
|
| 30 |
+
]
|
| 31 |
+
for payload, count, dim in cases:
|
| 32 |
+
with self.subTest(payload=payload), self.assertRaises(ValueError):
|
| 33 |
+
response_vectors(payload, count, dim)
|
| 34 |
+
|
| 35 |
+
def test_endpoint_prefix_and_local_api(self):
|
| 36 |
+
for base, expected in [('https://openrouter.ai/api/v1', 'https://openrouter.ai/api/v1/embeddings'), ('http://host.docker.internal:8000/v1/embeddings', 'http://host.docker.internal:8000/v1/embeddings')]:
|
| 37 |
+
with patch.dict(os.environ, {'EMBEDDING_BASE_URL': base, 'EMBEDDING_MODEL': 'chosen-model'}, clear=True):
|
| 38 |
+
self.assertEqual(api_settings()['endpoint'], expected)
|
| 39 |
+
|
| 40 |
+
def test_sqlite_cache_survives_restart(self):
|
| 41 |
+
with tempfile.TemporaryDirectory() as directory:
|
| 42 |
+
with locked_state(directory) as db:
|
| 43 |
+
self.assertEqual(cached_vectors(db, 'request', lambda: [[1, 0]]), [[1, 0]])
|
| 44 |
+
with locked_state(directory) as db:
|
| 45 |
+
self.assertEqual(cached_vectors(db, 'request', lambda: self.fail('API called twice')), [[1, 0]])
|
| 46 |
+
|
| 47 |
+
def test_identifiers_reject_cypher_injection(self):
|
| 48 |
+
with self.assertRaises(ValueError):
|
| 49 |
+
identifier('embedding` SET n.id=0 //')
|
| 50 |
+
|
| 51 |
+
def test_parquet_matches_ids_and_resume_skips_existing(self):
|
| 52 |
+
class Graph:
|
| 53 |
+
values = {'case-b': [0, 1]}
|
| 54 |
+
|
| 55 |
+
def check_source(self, *args):
|
| 56 |
+
pass
|
| 57 |
+
|
| 58 |
+
def missing(self, target, ids, prop):
|
| 59 |
+
return set(ids) - self.values.keys()
|
| 60 |
+
|
| 61 |
+
def write(self, target, prop, source, rows):
|
| 62 |
+
for row in rows:
|
| 63 |
+
self.values[row['key']] = row['vector']
|
| 64 |
+
|
| 65 |
+
with tempfile.TemporaryDirectory() as directory:
|
| 66 |
+
root = Path(directory)
|
| 67 |
+
(root / 'parquet').mkdir()
|
| 68 |
+
(root / 'manifest.json').write_text(json.dumps({'source_id': 'test'}))
|
| 69 |
+
vector = [1.0] + [0.0] * 4095
|
| 70 |
+
pq.write_table(pa.table({'case_id': ['case-b', 'case-a'], 'name_embedding': [vector, vector]}), root / 'parquet/cases.parquet')
|
| 71 |
+
graph = Graph()
|
| 72 |
+
self.assertEqual(load_vectors(graph, ['cases'], root, 1, None), {'cases': 1})
|
| 73 |
+
self.assertEqual(graph.values['case-a'], vector)
|
| 74 |
+
self.assertEqual(graph.values['case-b'], [0, 1])
|
| 75 |
+
self.assertEqual(load_vectors(graph, ['cases'], root, 1, None), {'cases': 0})
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
if __name__ == '__main__':
|
| 79 |
+
unittest.main()
|