Release LitGraph: 856 domains, 105159 entries, and 256227 papers
Browse filesFull SQLite database, search index, Parquet tables, read-only API, documentation, and checksums. Download-and-serve workflow verified locally.
- .gitattributes +2 -0
- CHANGELOG.md +20 -0
- README.md +157 -0
- SHA256SUMS +17 -0
- api/library_api.py +523 -0
- api/library_api_agent_prompt.md +67 -0
- api/library_api_docs.py +177 -0
- api/library_api_index.py +127 -0
- api/library_query.py +128 -0
- data/domain_papers.parquet +3 -0
- data/domains.parquet +3 -0
- data/insights.parquet +3 -0
- data/papers.parquet +3 -0
- data/problems.parquet +3 -0
- manifest.json +75 -0
- serve.py +64 -0
- snapshot/api_index.db +3 -0
- snapshot/domains.json +0 -0
- snapshot/library.db +3 -0
- statistics.json +47 -0
.gitattributes
CHANGED
|
@@ -58,3 +58,5 @@ saved_model/**/* 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
|
|
|
|
|
|
|
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
+
snapshot/api_index.db filter=lfs diff=lfs merge=lfs -text
|
| 62 |
+
snapshot/library.db filter=lfs diff=lfs merge=lfs -text
|
CHANGELOG.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Release 2026-11-12
|
| 2 |
+
|
| 3 |
+
Built from the frozen 856-domain export used for the manuscript library counts,
|
| 4 |
+
plus the original paper metadata used by the current API. Original IDs and
|
| 5 |
+
scientific fields are preserved.
|
| 6 |
+
|
| 7 |
+
Compared with the older live API snapshot:
|
| 8 |
+
|
| 9 |
+
- 97 additional insight/problem entries and 47 changed shared entries, all in
|
| 10 |
+
`end-to-end-driving`. Total entries are 105,159 instead of 105,062.
|
| 11 |
+
- All 256,129 available paper cards are included, instead of the 255,435-card
|
| 12 |
+
subset selected by the old database builder. This adds 694 existing cards;
|
| 13 |
+
it does not generate new cards.
|
| 14 |
+
- The catalog remains 856 domains and 256,227 unique papers. There are 98
|
| 15 |
+
metadata-only papers after including every available card.
|
| 16 |
+
- The API is rebuilt against this snapshot without changing the running
|
| 17 |
+
production database or altering historical experiment artifacts.
|
| 18 |
+
|
| 19 |
+
This is not a byte-identical copy of the database used by every historical run.
|
| 20 |
+
Use the original run provenance for reproduction of a historical experiment.
|
README.md
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
pretty_name: LitGraph
|
| 3 |
+
language:
|
| 4 |
+
- en
|
| 5 |
+
- zh
|
| 6 |
+
tags:
|
| 7 |
+
- scientific-literature
|
| 8 |
+
- research-ideation
|
| 9 |
+
- artificial-intelligence
|
| 10 |
+
size_categories:
|
| 11 |
+
- 100K<n<1M
|
| 12 |
+
configs:
|
| 13 |
+
- config_name: domains
|
| 14 |
+
data_files:
|
| 15 |
+
- split: train
|
| 16 |
+
path: data/domains.parquet
|
| 17 |
+
- config_name: insights
|
| 18 |
+
data_files:
|
| 19 |
+
- split: train
|
| 20 |
+
path: data/insights.parquet
|
| 21 |
+
- config_name: problems
|
| 22 |
+
data_files:
|
| 23 |
+
- split: train
|
| 24 |
+
path: data/problems.parquet
|
| 25 |
+
- config_name: papers
|
| 26 |
+
data_files:
|
| 27 |
+
- split: train
|
| 28 |
+
path: data/papers.parquet
|
| 29 |
+
- config_name: domain_papers
|
| 30 |
+
data_files:
|
| 31 |
+
- split: train
|
| 32 |
+
path: data/domain_papers.parquet
|
| 33 |
+
---
|
| 34 |
+
|
| 35 |
+
# LitGraph
|
| 36 |
+
|
| 37 |
+
LitGraph organizes AI literature into 856 research domains, with structured
|
| 38 |
+
insights, problems, supporting-paper links, and paper cards for research ideation.
|
| 39 |
+
This release is dated 2026-11-12.
|
| 40 |
+
|
| 41 |
+
| Component | Count |
|
| 42 |
+
|---|---:|
|
| 43 |
+
| Domains | 856 |
|
| 44 |
+
| Unique papers | 256,227 |
|
| 45 |
+
| Domain–paper assignments | 256,361 |
|
| 46 |
+
| Insights | 53,301 |
|
| 47 |
+
| Problems | 51,858 |
|
| 48 |
+
| Papers with structured cards | 256,129 |
|
| 49 |
+
| Papers with metadata only | 98 |
|
| 50 |
+
|
| 51 |
+
The insight/problem counts match the frozen export used for the manuscript's
|
| 52 |
+
library statistics. Domain-level and case-level entries are both included.
|
| 53 |
+
All available paper cards from that export are included, including 694 cards
|
| 54 |
+
absent from the older API database's subset of entry-linked papers.
|
| 55 |
+
|
| 56 |
+
## Contents
|
| 57 |
+
|
| 58 |
+
Two equivalent access formats are supplied:
|
| 59 |
+
|
| 60 |
+
- `snapshot/library.db`: complete entries and available structured paper cards,
|
| 61 |
+
with SQLite FTS5 search data.
|
| 62 |
+
- `snapshot/api_index.db`: field search index, paper metadata and abstracts,
|
| 63 |
+
domain catalog, and domain–paper mappings for the read-only HTTP API.
|
| 64 |
+
- `snapshot/domains.json`: the complete 856-domain catalog.
|
| 65 |
+
- `data/*.parquet`: typed tables for Hugging Face, Python, SQL engines, and
|
| 66 |
+
downstream processing. These preserve the original nested records in JSON
|
| 67 |
+
string columns so heterogeneous extraction fields do not silently disappear.
|
| 68 |
+
- `api/` and `serve.py`: read-only API implementation and portable launcher.
|
| 69 |
+
- `statistics.json`, `manifest.json`, `SHA256SUMS`, `CHANGELOG.md`: counts,
|
| 70 |
+
provenance identifiers, checksums, and differences from the older live API.
|
| 71 |
+
|
| 72 |
+
The Parquet configs are different tables, not experimental train/test splits;
|
| 73 |
+
`train` is a loader label for the full table.
|
| 74 |
+
|
| 75 |
+
## Use the local database and API
|
| 76 |
+
|
| 77 |
+
Download the complete dataset repository, then run from its root:
|
| 78 |
+
|
| 79 |
+
```bash
|
| 80 |
+
pip install huggingface_hub
|
| 81 |
+
hf download Einsia/LitGraph --repo-type dataset --local-dir LitGraph
|
| 82 |
+
cd LitGraph
|
| 83 |
+
```
|
| 84 |
+
|
| 85 |
+
```bash
|
| 86 |
+
python serve.py --verify-only
|
| 87 |
+
python serve.py --port 8895
|
| 88 |
+
```
|
| 89 |
+
|
| 90 |
+
Requires Python 3.10+ with SQLite FTS5. No model key, GPU, vector model, or paid API
|
| 91 |
+
is needed for retrieval. The launcher verifies the database and index against
|
| 92 |
+
the release checksums, then creates a local index copy to accommodate changed
|
| 93 |
+
file timestamps after download. The distributed snapshot files stay intact.
|
| 94 |
+
Allow approximately 0.8 GB of extra space for that local index copy.
|
| 95 |
+
|
| 96 |
+
```text
|
| 97 |
+
http://127.0.0.1:8895/llms.txt
|
| 98 |
+
http://127.0.0.1:8895/openapi.json
|
| 99 |
+
http://127.0.0.1:8895/api/v1/stats
|
| 100 |
+
http://127.0.0.1:8895/api/v1/domains?limit=100
|
| 101 |
+
http://127.0.0.1:8895/api/v1/search?q=distillation&kind=insight&mode=any
|
| 102 |
+
```
|
| 103 |
+
|
| 104 |
+
The API uses field-specific lexical BM25 with Chinese bigram tokenization.
|
| 105 |
+
It does not implement vector search. Hugging Face stores the downloadable
|
| 106 |
+
snapshot; uploading this repository does not itself deploy an HTTP API.
|
| 107 |
+
|
| 108 |
+
## Read Parquet
|
| 109 |
+
|
| 110 |
+
Load an individual table directly from Hugging Face:
|
| 111 |
+
|
| 112 |
+
```python
|
| 113 |
+
from datasets import load_dataset
|
| 114 |
+
insights = load_dataset('Einsia/LitGraph', 'insights', split='train')
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
Or read the downloaded files locally:
|
| 118 |
+
|
| 119 |
+
```python
|
| 120 |
+
import pyarrow.parquet as pq
|
| 121 |
+
insights = pq.read_table('data/insights.parquet').to_pandas()
|
| 122 |
+
papers = pq.read_table('data/papers.parquet', columns=[
|
| 123 |
+
'paper_id', 'title', 'abstract', 'source_card_available'
|
| 124 |
+
]).to_pandas()
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
| Table | Main columns |
|
| 128 |
+
|---|---|
|
| 129 |
+
| domains | id, name, paper_count, domain_json |
|
| 130 |
+
| insights / problems | id, domain_id, kind, tier, statement, supporting_paper_ids, entry_json |
|
| 131 |
+
| papers | paper_id, title, year, venue, arxiv, abstract, source_card_available, domain_ids, metadata_json, card_json |
|
| 132 |
+
| domain_papers | domain_id, paper_id |
|
| 133 |
+
|
| 134 |
+
Parse `entry_json`, `card_json`, `metadata_json`, or `domain_json` with
|
| 135 |
+
`json.loads` to access the complete nested record. Original scientific fields
|
| 136 |
+
are retained. Pipeline response traces, prompts, usage logs, and internal
|
| 137 |
+
ingestion-source fields are excluded. Paper years retain their source string
|
| 138 |
+
representation; no silent correction of known source anomalies is applied.
|
| 139 |
+
`metadata_json` also preserves the upstream intuition/problem-definition fields
|
| 140 |
+
where present, which the current HTTP API does not expose.
|
| 141 |
+
|
| 142 |
+
## Evidence and version scope
|
| 143 |
+
|
| 144 |
+
This dataset contains metadata, abstracts, and extracted/aggregated research
|
| 145 |
+
materials. It does **not** contain a full-text or PDF collection. A card's
|
| 146 |
+
`source=fulltext` means its extraction used full text, not that the full text is
|
| 147 |
+
included. Some cards do not record their extraction depth; see `statistics.json`.
|
| 148 |
+
Model-extracted statements can contain errors and should be checked against the
|
| 149 |
+
linked original publications. Paper IDs are local numeric IDs, not OpenAlex IDs.
|
| 150 |
+
|
| 151 |
+
This is a current corpus, not a historical-cutoff or benchmark-masked snapshot.
|
| 152 |
+
The 38-domain IdeaX benchmark data, run trajectories, generated ideas, scores,
|
| 153 |
+
credentials, and working directories are outside this dataset release.
|
| 154 |
+
|
| 155 |
+
A dataset-wide reuse license has not yet been specified. This repository does
|
| 156 |
+
not grant rights to the original publications or assert a blanket license over
|
| 157 |
+
third-party paper material.
|
SHA256SUMS
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
076a8d3b368e80173e57088552781cdbba73b80c94d8bc6f8d16d562d783176f CHANGELOG.md
|
| 2 |
+
f33e3bea13bba1d372ce1c35bff014e4859b0c0341bcf433512b89cc7d79189b README.md
|
| 3 |
+
17b3d21d76799e06ede2bdcb6c89fec5367eb456f0f60234ab13e6ef6dc0e5fe api/library_api.py
|
| 4 |
+
bcd934753c00d22a3d1267f01400595d0eb16fbe882426fd1e0ad2292542b772 api/library_api_agent_prompt.md
|
| 5 |
+
8f05bf8abd6829f476dc57da95d207f843269b81ad410162cbba4b6833eb0581 api/library_api_docs.py
|
| 6 |
+
05363d0c31d73df8919c8d08fff69571bb29701fc701ee35fa944facfb32b4ab api/library_api_index.py
|
| 7 |
+
a4a389d9e9589ab4cda2adb6da1aad53a3ecf3b7970dbe7047f075c534a8a617 api/library_query.py
|
| 8 |
+
70b7b44dad6396cebb6cb341145012a2ccda6bb0090a76d15a760b520cd1c3e5 data/domain_papers.parquet
|
| 9 |
+
d05559df3c7a6e814bf70a36500283928bc87a42edf7bf51a676286cd28b29e6 data/domains.parquet
|
| 10 |
+
82d22c7b8919c9122f52d403bcc9bb856fc8ef9b6c800cb54f1d9cbddd42f2fe data/insights.parquet
|
| 11 |
+
62101a0f4a20e091d59f8ed4233064bd6a3f169a075df9d70e2f1f8fda27fae9 data/papers.parquet
|
| 12 |
+
b9f3009c56da9877d6bab359fa3d85b2587c56a05bee22980bbc6c875d798745 data/problems.parquet
|
| 13 |
+
c21a0ab860559e0114c65e060b7ae51a78ddb5710e1b4fe49d86e5f2c30224f1 serve.py
|
| 14 |
+
222b0300bed5ff27ede83067301d6958d5ba5d4a397a2eda24814c6dbc119b8a snapshot/api_index.db
|
| 15 |
+
dc5e74fd69f1a36c5b3b618274639b2450a5256d2f254d79603e3cc037344d95 snapshot/domains.json
|
| 16 |
+
62a604878de989d0189db479e64bef0edfb243e94a67f39a2885620069d133fd snapshot/library.db
|
| 17 |
+
ac9f0dc06be6ef7e78e62ed99148cb9489fcbedb0a8a70b55d272abe320d2207 statistics.json
|
api/library_api.py
ADDED
|
@@ -0,0 +1,523 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Read-only HTTP access to the problem/insight library used by ideaX."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
from contextlib import contextmanager
|
| 6 |
+
import copy
|
| 7 |
+
import hashlib
|
| 8 |
+
import hmac
|
| 9 |
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
| 10 |
+
import json
|
| 11 |
+
import os
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
import re
|
| 14 |
+
import secrets
|
| 15 |
+
import sqlite3
|
| 16 |
+
import threading
|
| 17 |
+
import time
|
| 18 |
+
from urllib.parse import parse_qs, unquote, urlsplit
|
| 19 |
+
|
| 20 |
+
from library_query import tokens
|
| 21 |
+
from library_api_index import FIELDS, INDEX_VERSION, arxiv_id, fingerprint, supporting_paper_count
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class APIError(Exception):
|
| 25 |
+
def __init__(self, status, code, message):
|
| 26 |
+
self.status, self.code, self.message = status, code, message
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def bounded_integer(value, name, default, low, high):
|
| 30 |
+
if value is None:
|
| 31 |
+
return default
|
| 32 |
+
try:
|
| 33 |
+
number = int(value)
|
| 34 |
+
except (ValueError, TypeError):
|
| 35 |
+
raise APIError(400, 'invalid_parameter', f'{name} must be an integer') from None
|
| 36 |
+
if not low <= number <= high:
|
| 37 |
+
raise APIError(400, 'invalid_parameter', f'{name} must be between {low} and {high}')
|
| 38 |
+
return number
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class Library:
|
| 42 |
+
def __init__(self, database, index, query_timeout=5.0):
|
| 43 |
+
self.path = Path(database).resolve(strict=True)
|
| 44 |
+
self.index = Path(index).resolve(strict=True)
|
| 45 |
+
self.query_timeout = query_timeout
|
| 46 |
+
self._domain_catalog = None
|
| 47 |
+
self._domain_catalog_lock = threading.Lock()
|
| 48 |
+
with sqlite3.connect(self.index.as_uri() + '?mode=ro', uri=True) as con:
|
| 49 |
+
if con.execute("SELECT value FROM metadata WHERE key='version'").fetchone()[0] != INDEX_VERSION:
|
| 50 |
+
raise ValueError('Search index version is unsupported; rebuild the index')
|
| 51 |
+
self.source_fingerprint = json.loads(con.execute("SELECT value FROM metadata WHERE key='source'").fetchone()[0])
|
| 52 |
+
if self.source_fingerprint != fingerprint(self.path):
|
| 53 |
+
raise ValueError('Search index is stale; rebuild it for this library snapshot')
|
| 54 |
+
with self.connect() as con:
|
| 55 |
+
for table in ('entries', 'papers', 'search'):
|
| 56 |
+
if not con.execute('SELECT 1 FROM sqlite_master WHERE name=?', (table,)).fetchone():
|
| 57 |
+
raise ValueError(f'Missing required library table: {table}')
|
| 58 |
+
|
| 59 |
+
@contextmanager
|
| 60 |
+
def connect(self):
|
| 61 |
+
if self.source_fingerprint != fingerprint(self.path):
|
| 62 |
+
raise APIError(503, 'stale_index', 'Library snapshot changed; search index must be rebuilt')
|
| 63 |
+
con = sqlite3.connect(self.path.as_uri() + '?mode=ro', uri=True, timeout=2.0)
|
| 64 |
+
try:
|
| 65 |
+
con.execute('PRAGMA query_only=ON')
|
| 66 |
+
con.execute('ATTACH DATABASE ? AS idx', (self.index.as_uri() + '?mode=ro',))
|
| 67 |
+
deadline = time.monotonic() + self.query_timeout
|
| 68 |
+
con.set_progress_handler(lambda: time.monotonic() > deadline, 1000)
|
| 69 |
+
yield con
|
| 70 |
+
finally:
|
| 71 |
+
con.close()
|
| 72 |
+
|
| 73 |
+
def stats(self):
|
| 74 |
+
with self.connect() as con:
|
| 75 |
+
counts = dict(con.execute('SELECT kind,count(*) FROM entries GROUP BY kind'))
|
| 76 |
+
return dict(entries=sum(counts.values()), by_kind=counts,
|
| 77 |
+
units=con.execute('SELECT count(DISTINCT unit) FROM entries').fetchone()[0],
|
| 78 |
+
domains=con.execute('SELECT count(*) FROM idx.domains').fetchone()[0],
|
| 79 |
+
papers=con.execute('SELECT count(*) FROM idx.papers').fetchone()[0],
|
| 80 |
+
source_cards=con.execute('SELECT count(*) FROM main.papers').fetchone()[0],
|
| 81 |
+
snapshot_modified_at=int(self.path.stat().st_mtime))
|
| 82 |
+
|
| 83 |
+
def domains(self, params):
|
| 84 |
+
if set(params) - {'q', 'limit', 'offset'}:
|
| 85 |
+
raise APIError(400, 'invalid_parameter', 'Unknown domain query parameter')
|
| 86 |
+
limit = bounded_integer(params.get('limit'), 'limit', 50, 1, 100)
|
| 87 |
+
offset = bounded_integer(params.get('offset'), 'offset', 0, 0, 10000)
|
| 88 |
+
terms = tokens(params.get('q', ''))
|
| 89 |
+
result = []
|
| 90 |
+
for identifier, data in self.domain_catalog().items():
|
| 91 |
+
text = (identifier + ' ' + data.get('name', '')).lower()
|
| 92 |
+
if terms and not all(t in text for t in terms):
|
| 93 |
+
continue
|
| 94 |
+
result.append(data)
|
| 95 |
+
total = len(result)
|
| 96 |
+
return copy.deepcopy(result[offset:offset + limit]), {'count': len(result[offset:offset + limit]), 'total': total, 'limit': limit,
|
| 97 |
+
'has_more': offset + limit < total,
|
| 98 |
+
'next_offset': offset + limit if offset + limit < total else None}
|
| 99 |
+
|
| 100 |
+
def domain_catalog(self):
|
| 101 |
+
"""Reuse exact counts for the verified read-only source, never a stale index.
|
| 102 |
+
|
| 103 |
+
Thirty scouts used to repeat whole-library GROUP BY joins on each page.
|
| 104 |
+
Check the source fingerprint on every use, and build once under a lock.
|
| 105 |
+
"""
|
| 106 |
+
if self.source_fingerprint != fingerprint(self.path):
|
| 107 |
+
raise APIError(503, 'stale_index', 'Library snapshot changed; search index must be rebuilt')
|
| 108 |
+
with self._domain_catalog_lock:
|
| 109 |
+
if self._domain_catalog is None:
|
| 110 |
+
self._domain_catalog = self._load_domain_catalog()
|
| 111 |
+
return self._domain_catalog
|
| 112 |
+
|
| 113 |
+
def _load_domain_catalog(self):
|
| 114 |
+
with self.connect() as con:
|
| 115 |
+
kinds = {}
|
| 116 |
+
for unit, kind, count in con.execute('SELECT unit,kind,count(*) FROM entries GROUP BY unit,kind'):
|
| 117 |
+
kinds.setdefault(unit, {})[kind] = count
|
| 118 |
+
paper_counts = {r[0]: (r[1], r[2]) for r in con.execute(
|
| 119 |
+
'SELECT d.domain_id,count(*),sum(p.has_source_card) FROM idx.domain_papers d JOIN idx.papers p ON p.id=d.paper_id GROUP BY d.domain_id')}
|
| 120 |
+
result = {}
|
| 121 |
+
for identifier, raw in con.execute('SELECT id,data FROM idx.domains ORDER BY id'):
|
| 122 |
+
data = json.loads(raw)
|
| 123 |
+
paper_count, card_count = paper_counts.get(identifier, (0, 0))
|
| 124 |
+
data['counts'] = {'problems': kinds.get(identifier, {}).get('problem', 0),
|
| 125 |
+
'insights': kinds.get(identifier, {}).get('insight', 0),
|
| 126 |
+
'papers': paper_count, 'source_cards': card_count}
|
| 127 |
+
result[identifier] = data
|
| 128 |
+
return result
|
| 129 |
+
|
| 130 |
+
def domain(self, identifier):
|
| 131 |
+
data = self.domain_catalog().get(identifier)
|
| 132 |
+
if data is None:
|
| 133 |
+
raise APIError(404, 'not_found', 'Unknown research domain')
|
| 134 |
+
return copy.deepcopy(data)
|
| 135 |
+
|
| 136 |
+
def domain_papers(self, identifier, params):
|
| 137 |
+
self.domain(identifier)
|
| 138 |
+
if set(params) - {'q', 'limit', 'after'}:
|
| 139 |
+
raise APIError(400, 'invalid_parameter', 'Use q,limit,after for domain papers')
|
| 140 |
+
limit = bounded_integer(params.get('limit'), 'limit', 20, 1, 100)
|
| 141 |
+
sql = 'SELECT p.id,p.data FROM idx.domain_papers d JOIN idx.papers p ON p.id=d.paper_id WHERE d.domain_id=?'
|
| 142 |
+
args = [identifier]
|
| 143 |
+
if params.get('after'):
|
| 144 |
+
sql += ' AND p.id>?'
|
| 145 |
+
args.append(params['after'])
|
| 146 |
+
for term in tokens(params.get('q', '')):
|
| 147 |
+
sql += " AND lower(json_extract(p.data,'$.title')) LIKE ?"
|
| 148 |
+
args.append('%' + term + '%')
|
| 149 |
+
sql += ' ORDER BY p.id LIMIT ?'
|
| 150 |
+
args.append(limit + 1)
|
| 151 |
+
with self.connect() as con:
|
| 152 |
+
rows = con.execute(sql, args).fetchall()
|
| 153 |
+
more, rows = len(rows) > limit, rows[:limit]
|
| 154 |
+
data = [{k: v for k, v in json.loads(row[1]).items() if k != 'abstract'} for row in rows]
|
| 155 |
+
return data, {'count': len(data), 'limit': limit, 'has_more': more, 'next_after': rows[-1][0] if more else None}
|
| 156 |
+
|
| 157 |
+
def units(self):
|
| 158 |
+
with self.connect() as con:
|
| 159 |
+
counts = {}
|
| 160 |
+
for unit, kind, count in con.execute('SELECT unit,kind,count(*) FROM entries GROUP BY unit,kind'):
|
| 161 |
+
counts.setdefault(unit, {'id': unit, 'problem': 0, 'insight': 0})[kind] = count
|
| 162 |
+
# One indexed lookup per unit avoids decoding every entry's JSON.
|
| 163 |
+
for unit, value in counts.items():
|
| 164 |
+
data = con.execute('SELECT data FROM entries WHERE unit=? AND kind=? LIMIT 1',
|
| 165 |
+
(unit, 'problem' if value['problem'] else 'insight')).fetchone()[0]
|
| 166 |
+
value['name'] = json.loads(data).get('unit_name', unit)
|
| 167 |
+
return [counts[key] for key in sorted(counts)]
|
| 168 |
+
|
| 169 |
+
def get(self, table, identifier):
|
| 170 |
+
if table not in ('entries', 'papers'):
|
| 171 |
+
raise ValueError('Unsupported resource')
|
| 172 |
+
with self.connect() as con:
|
| 173 |
+
row = con.execute(f'SELECT data FROM {table} WHERE id=?', (identifier,)).fetchone()
|
| 174 |
+
if table == 'papers':
|
| 175 |
+
meta = con.execute('SELECT data FROM idx.papers WHERE id=?', (identifier,)).fetchone()
|
| 176 |
+
if row or meta:
|
| 177 |
+
data = json.loads(meta[0]) if meta else {}
|
| 178 |
+
data.update(json.loads(row[0]) if row else {})
|
| 179 |
+
data['source_card_available'] = row is not None
|
| 180 |
+
data['domains'] = [x[0] for x in con.execute('SELECT domain_id FROM idx.domain_papers WHERE paper_id=? ORDER BY domain_id', (identifier,))]
|
| 181 |
+
return data
|
| 182 |
+
if row is None:
|
| 183 |
+
raise APIError(404, 'not_found', 'No matching resource')
|
| 184 |
+
data = json.loads(row[0])
|
| 185 |
+
data['paper_count'] = supporting_paper_count(data)
|
| 186 |
+
return data
|
| 187 |
+
|
| 188 |
+
def by_arxiv(self, identifier):
|
| 189 |
+
normalized = arxiv_id(identifier)
|
| 190 |
+
if not normalized:
|
| 191 |
+
raise APIError(400, 'invalid_parameter', 'Invalid arXiv ID')
|
| 192 |
+
with self.connect() as con:
|
| 193 |
+
rows = con.execute('SELECT id FROM idx.papers WHERE arxiv=? ORDER BY id',
|
| 194 |
+
(normalized,)).fetchall()
|
| 195 |
+
if not rows:
|
| 196 |
+
raise APIError(404, 'not_found', 'No paper matches this arXiv ID')
|
| 197 |
+
return [self.get('papers', row[0]) for row in rows]
|
| 198 |
+
|
| 199 |
+
def batch(self, identifiers):
|
| 200 |
+
if not isinstance(identifiers, list) or not 1 <= len(identifiers) <= 50:
|
| 201 |
+
raise APIError(400, 'invalid_parameter', 'ids must contain 1–50 numeric paper IDs')
|
| 202 |
+
if any(isinstance(x, bool) or not isinstance(x, (str, int)) or not re.fullmatch(r'[0-9]{1,20}', str(x)) for x in identifiers):
|
| 203 |
+
raise APIError(400, 'invalid_parameter', 'Each paper ID must be numeric')
|
| 204 |
+
identifiers = list(dict.fromkeys(str(x) for x in identifiers))
|
| 205 |
+
papers, missing = [], []
|
| 206 |
+
for identifier in identifiers:
|
| 207 |
+
try:
|
| 208 |
+
papers.append(self.get('papers', identifier))
|
| 209 |
+
except APIError as exc:
|
| 210 |
+
if exc.status != 404:
|
| 211 |
+
raise
|
| 212 |
+
missing.append(identifier)
|
| 213 |
+
return {'papers': papers, 'missing_ids': missing}
|
| 214 |
+
|
| 215 |
+
def entries(self, params):
|
| 216 |
+
unknown = set(params) - {'q', 'kind', 'unit', 'limit', 'offset', 'after', 'mode', 'fields', 'sort'}
|
| 217 |
+
if unknown:
|
| 218 |
+
raise APIError(400, 'invalid_parameter', 'Unknown query parameter')
|
| 219 |
+
limit = bounded_integer(params.get('limit'), 'limit', 20, 1, 100)
|
| 220 |
+
offset = bounded_integer(params.get('offset'), 'offset', 0, 0, 10000)
|
| 221 |
+
kind = params.get('kind')
|
| 222 |
+
if kind is not None and kind not in ('problem', 'insight'):
|
| 223 |
+
raise APIError(400, 'invalid_parameter', 'kind must be problem or insight')
|
| 224 |
+
query = params.get('q')
|
| 225 |
+
sort = params.get('sort', 'relevance' if query is not None else 'id')
|
| 226 |
+
if sort not in ('id', 'relevance', 'paper_count'):
|
| 227 |
+
raise APIError(400, 'invalid_parameter', 'sort must be id, relevance or paper_count')
|
| 228 |
+
if sort == 'relevance' and query is None:
|
| 229 |
+
raise APIError(400, 'invalid_parameter', 'sort=relevance requires q')
|
| 230 |
+
mode = params.get('mode', 'all')
|
| 231 |
+
if mode not in ('all', 'any'):
|
| 232 |
+
raise APIError(400, 'invalid_parameter', 'mode must be all or any')
|
| 233 |
+
fields = params.get('fields', ','.join(FIELDS)).split(',')
|
| 234 |
+
if not fields or not set(fields) <= set(FIELDS):
|
| 235 |
+
raise APIError(400, 'invalid_parameter', 'fields must be a comma-separated subset of: ' + ','.join(FIELDS))
|
| 236 |
+
terms = tokens(query) if query is not None else []
|
| 237 |
+
if query is not None and (not terms or len(query) > 500 or len(terms) > 64):
|
| 238 |
+
raise APIError(400, 'invalid_parameter', 'q needs 1–64 searchable terms and at most 500 characters')
|
| 239 |
+
if 'after' in params and (query is not None or offset or sort != 'id'):
|
| 240 |
+
raise APIError(400, 'invalid_parameter', 'after requires ID-ordered browsing without q or offset; use offset for paper_count sorting')
|
| 241 |
+
predicates, args = [], []
|
| 242 |
+
sql = 'SELECT e.id,e.data,s.paper_count'
|
| 243 |
+
if terms:
|
| 244 |
+
sql += ',bm25(entry_fts)'
|
| 245 |
+
sql += ' FROM idx.entries s JOIN main.entries e ON e.id=s.id'
|
| 246 |
+
if terms:
|
| 247 |
+
sql += ' JOIN idx.entry_fts ON entry_fts.id=s.id'
|
| 248 |
+
predicates.append('entry_fts MATCH ?')
|
| 249 |
+
operator = ' AND ' if mode == 'all' else ' OR '
|
| 250 |
+
args.append('{' + ' '.join(fields) + '}: (' + operator.join('"' + term + '"' for term in terms) + ')')
|
| 251 |
+
for key in ('kind', 'unit'):
|
| 252 |
+
if params.get(key) is not None:
|
| 253 |
+
predicates.append(f's.{key}=?')
|
| 254 |
+
args.append(params[key])
|
| 255 |
+
if params.get('after'):
|
| 256 |
+
predicates.append('s.id>?')
|
| 257 |
+
args.append(params['after'])
|
| 258 |
+
if predicates:
|
| 259 |
+
sql += ' WHERE ' + ' AND '.join(predicates)
|
| 260 |
+
ordering = {'paper_count': 's.paper_count DESC,s.id', 'relevance': 'bm25(entry_fts),s.id', 'id': 's.id'}
|
| 261 |
+
sql += ' ORDER BY ' + ordering[sort] + ' LIMIT ? OFFSET ?'
|
| 262 |
+
args += [limit + 1, offset]
|
| 263 |
+
with self.connect() as con:
|
| 264 |
+
rows = con.execute(sql, args).fetchall()
|
| 265 |
+
more, rows = len(rows) > limit, rows[:limit]
|
| 266 |
+
output_fields = ('id', 'kind', 'unit', 'unit_name', 'statement', 'mechanism', 'scope', 'techniques', 'supporting_papers')
|
| 267 |
+
data = [{key: entry.get(key) for key in output_fields} for entry in (json.loads(row[1]) for row in rows)]
|
| 268 |
+
for value, row in zip(data, rows):
|
| 269 |
+
value['paper_count'] = row[2]
|
| 270 |
+
if terms:
|
| 271 |
+
value['score'] = row[3]
|
| 272 |
+
page = dict(limit=limit, count=len(data), has_more=more, sort=sort)
|
| 273 |
+
if terms or offset or sort == 'paper_count':
|
| 274 |
+
page['next_offset'] = offset + limit if more and offset + limit <= 10000 else None
|
| 275 |
+
else:
|
| 276 |
+
page['next_after'] = rows[-1][0] if more else None
|
| 277 |
+
return data, page
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
class Credentials:
|
| 281 |
+
"""Load only token hashes on the server; replacing the file revokes keys immediately."""
|
| 282 |
+
def __init__(self, path):
|
| 283 |
+
self.path = Path(path).resolve(strict=True)
|
| 284 |
+
self.clients()
|
| 285 |
+
|
| 286 |
+
def clients(self):
|
| 287 |
+
value = json.loads(self.path.read_text())
|
| 288 |
+
clients = value.get('clients', {})
|
| 289 |
+
if not clients or any(not re.fullmatch(r'[a-f0-9]{64}', digest) for digest in clients.values()):
|
| 290 |
+
raise ValueError('Credentials must contain named SHA-256 token hashes')
|
| 291 |
+
return clients
|
| 292 |
+
|
| 293 |
+
def authenticate(self, authorization):
|
| 294 |
+
if not authorization or not authorization.startswith('Bearer '):
|
| 295 |
+
raise APIError(401, 'unauthorized', 'A Bearer API key is required')
|
| 296 |
+
digest = hashlib.sha256(authorization[7:].encode()).hexdigest()
|
| 297 |
+
for name, expected in self.clients().items():
|
| 298 |
+
if hmac.compare_digest(digest, expected):
|
| 299 |
+
return name
|
| 300 |
+
raise APIError(401, 'unauthorized', 'Invalid API key')
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
class Server(ThreadingHTTPServer):
|
| 304 |
+
daemon_threads = True
|
| 305 |
+
allow_reuse_address = True
|
| 306 |
+
|
| 307 |
+
def __init__(self, address, library, credentials=None):
|
| 308 |
+
self.library, self.credentials = library, credentials
|
| 309 |
+
self.queries = threading.BoundedSemaphore(16)
|
| 310 |
+
super().__init__(address, Handler)
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
class Handler(BaseHTTPRequestHandler):
|
| 314 |
+
server_version = 'ideaX-library-api/1'
|
| 315 |
+
sys_version = ''
|
| 316 |
+
|
| 317 |
+
def setup(self):
|
| 318 |
+
super().setup()
|
| 319 |
+
self.connection.settimeout(10)
|
| 320 |
+
|
| 321 |
+
def log_message(self, *args):
|
| 322 |
+
pass
|
| 323 |
+
|
| 324 |
+
def reply(self, status, body, extra=None):
|
| 325 |
+
is_text = isinstance(body, str)
|
| 326 |
+
data = body.encode() if is_text else json.dumps(body, ensure_ascii=False, separators=(',', ':')).encode()
|
| 327 |
+
self.send_response(status)
|
| 328 |
+
for key, value in {'Content-Type': 'text/plain; charset=utf-8' if is_text else 'application/json; charset=utf-8',
|
| 329 |
+
'Content-Length': str(len(data)), 'Cache-Control': 'no-store',
|
| 330 |
+
'X-Content-Type-Options': 'nosniff', **(extra or {})}.items():
|
| 331 |
+
self.send_header(key, value)
|
| 332 |
+
self.end_headers()
|
| 333 |
+
if self.command != 'HEAD':
|
| 334 |
+
self.wfile.write(data)
|
| 335 |
+
|
| 336 |
+
def do_HEAD(self):
|
| 337 |
+
self.do_GET()
|
| 338 |
+
|
| 339 |
+
def do_GET(self):
|
| 340 |
+
acquired = False
|
| 341 |
+
try:
|
| 342 |
+
if len(self.path) > 4096:
|
| 343 |
+
raise APIError(414, 'uri_too_long', 'Request URI is too long')
|
| 344 |
+
parsed = urlsplit(self.path)
|
| 345 |
+
route = unquote(parsed.path)
|
| 346 |
+
if route in ('/healthz', '/health'):
|
| 347 |
+
return self.reply(200, {'ok': True, 'service': 'ideaX library', 'read_only': True})
|
| 348 |
+
if route in ('/', '/llms.txt', '/openapi.json'):
|
| 349 |
+
from library_api_docs import llms_text, openapi
|
| 350 |
+
return self.reply(200, openapi(bool(self.server.credentials)) if route == '/openapi.json' else llms_text(bool(self.server.credentials)))
|
| 351 |
+
if self.server.credentials:
|
| 352 |
+
self.server.credentials.authenticate(self.headers.get('Authorization'))
|
| 353 |
+
if route.startswith('/api/v1/'):
|
| 354 |
+
route = route[4:]
|
| 355 |
+
acquired = self.server.queries.acquire(blocking=False)
|
| 356 |
+
if not acquired:
|
| 357 |
+
raise APIError(503, 'busy', 'Too many concurrent queries; retry later')
|
| 358 |
+
raw = parse_qs(parsed.query, keep_blank_values=True, max_num_fields=16)
|
| 359 |
+
if any(len(v) != 1 for v in raw.values()):
|
| 360 |
+
raise APIError(400, 'invalid_parameter', 'Query parameters must not be repeated')
|
| 361 |
+
params = {k: v[0] for k, v in raw.items()}
|
| 362 |
+
page = None
|
| 363 |
+
domain_match = re.fullmatch(r'/v1/domains/([a-zA-Z0-9_.-]{1,200})(?:/(problems|insights|papers))?', route)
|
| 364 |
+
if route == '/v1/domains':
|
| 365 |
+
data, page = self.server.library.domains(params)
|
| 366 |
+
elif domain_match:
|
| 367 |
+
identifier, resource = domain_match.groups()
|
| 368 |
+
if resource is None:
|
| 369 |
+
if params:
|
| 370 |
+
raise APIError(400, 'invalid_parameter', 'Domain detail takes no query parameters')
|
| 371 |
+
data = self.server.library.domain(identifier)
|
| 372 |
+
elif resource == 'papers':
|
| 373 |
+
data, page = self.server.library.domain_papers(identifier, params)
|
| 374 |
+
else:
|
| 375 |
+
self.server.library.domain(identifier)
|
| 376 |
+
if 'kind' in params or 'unit' in params:
|
| 377 |
+
raise APIError(400, 'invalid_parameter', 'Domain and kind are fixed by this endpoint')
|
| 378 |
+
data, page = self.server.library.entries(dict(params, unit=identifier, kind=resource[:-1]))
|
| 379 |
+
elif route in ('/v1/entries', '/v1/search'):
|
| 380 |
+
if route == '/v1/search' and 'q' not in params:
|
| 381 |
+
raise APIError(400, 'invalid_parameter', 'q is required for search')
|
| 382 |
+
data, page = self.server.library.entries(params)
|
| 383 |
+
elif route == '/v1/papers/by-arxiv':
|
| 384 |
+
if set(params) != {'id'}:
|
| 385 |
+
raise APIError(400, 'invalid_parameter', 'Only the id parameter is required')
|
| 386 |
+
data = self.server.library.by_arxiv(params['id'])
|
| 387 |
+
elif params:
|
| 388 |
+
raise APIError(400, 'invalid_parameter', 'This endpoint does not accept query parameters')
|
| 389 |
+
elif route == '/v1/stats':
|
| 390 |
+
data = self.server.library.stats()
|
| 391 |
+
elif route == '/v1/units':
|
| 392 |
+
data = self.server.library.units()
|
| 393 |
+
elif re.fullmatch(r'/v1/entries/[a-zA-Z0-9_.-]{1,200}', route):
|
| 394 |
+
data = self.server.library.get('entries', route.rsplit('/', 1)[1])
|
| 395 |
+
elif re.fullmatch(r'/v1/papers/[0-9]{1,20}', route):
|
| 396 |
+
data = self.server.library.get('papers', route.rsplit('/', 1)[1])
|
| 397 |
+
else:
|
| 398 |
+
raise APIError(404, 'not_found', 'Unknown endpoint')
|
| 399 |
+
result = {'ok': True, 'data': data}
|
| 400 |
+
if page is not None:
|
| 401 |
+
result['page'] = page
|
| 402 |
+
self.reply(200, result)
|
| 403 |
+
except APIError as exc:
|
| 404 |
+
self.reply(exc.status, {'ok': False, 'error': {'code': exc.code, 'message': exc.message}},
|
| 405 |
+
{'WWW-Authenticate': 'Bearer'} if exc.status == 401 else None)
|
| 406 |
+
except ValueError:
|
| 407 |
+
self.reply(400, {'ok': False, 'error': {'code': 'invalid_request', 'message': 'Invalid request'}})
|
| 408 |
+
except sqlite3.OperationalError:
|
| 409 |
+
self.reply(503, {'ok': False, 'error': {'code': 'query_unavailable', 'message': 'Query timed out or database unavailable'}})
|
| 410 |
+
except (BrokenPipeError, ConnectionResetError, TimeoutError):
|
| 411 |
+
pass
|
| 412 |
+
except Exception:
|
| 413 |
+
self.reply(500, {'ok': False, 'error': {'code': 'internal_error', 'message': 'Internal server error'}})
|
| 414 |
+
finally:
|
| 415 |
+
if acquired:
|
| 416 |
+
self.server.queries.release()
|
| 417 |
+
|
| 418 |
+
def reject_write(self):
|
| 419 |
+
self.close_connection = True
|
| 420 |
+
self.reply(405, {'ok': False, 'error': {'code': 'read_only', 'message': 'No data mutations are supported'}},
|
| 421 |
+
{'Allow': 'GET, HEAD', 'Connection': 'close'})
|
| 422 |
+
|
| 423 |
+
def do_POST(self):
|
| 424 |
+
acquired = False
|
| 425 |
+
try:
|
| 426 |
+
if self.path not in ('/api/v1/papers/batch', '/v1/papers/batch'):
|
| 427 |
+
return self.reject_write()
|
| 428 |
+
if self.server.credentials:
|
| 429 |
+
self.server.credentials.authenticate(self.headers.get('Authorization'))
|
| 430 |
+
if self.headers.get('Transfer-Encoding') or len(self.headers.get_all('Content-Length', [])) != 1:
|
| 431 |
+
raise APIError(400, 'invalid_request', 'One Content-Length header is required')
|
| 432 |
+
if self.headers.get('Content-Type', '').split(';')[0].strip().lower() != 'application/json':
|
| 433 |
+
raise APIError(415, 'invalid_content_type', 'Use application/json')
|
| 434 |
+
size = bounded_integer(self.headers.get('Content-Length'), 'Content-Length', 0, 1, 8192)
|
| 435 |
+
body = json.loads(self.rfile.read(size))
|
| 436 |
+
if not isinstance(body, dict) or set(body) != {'ids'}:
|
| 437 |
+
raise APIError(400, 'invalid_request', 'Expected an object with only the ids field')
|
| 438 |
+
acquired = self.server.queries.acquire(blocking=False)
|
| 439 |
+
if not acquired:
|
| 440 |
+
raise APIError(503, 'busy', 'Too many concurrent queries; retry later')
|
| 441 |
+
self.reply(200, {'ok': True, 'data': self.server.library.batch(body['ids'])})
|
| 442 |
+
except APIError as exc:
|
| 443 |
+
self.close_connection = True
|
| 444 |
+
self.reply(exc.status, {'ok': False, 'error': {'code': exc.code, 'message': exc.message}})
|
| 445 |
+
except (ValueError, UnicodeError):
|
| 446 |
+
self.close_connection = True
|
| 447 |
+
self.reply(400, {'ok': False, 'error': {'code': 'invalid_json', 'message': 'Invalid JSON body'}})
|
| 448 |
+
except sqlite3.OperationalError:
|
| 449 |
+
self.reply(503, {'ok': False, 'error': {'code': 'query_unavailable', 'message': 'Database unavailable'}})
|
| 450 |
+
except (BrokenPipeError, ConnectionResetError, TimeoutError):
|
| 451 |
+
self.close_connection = True
|
| 452 |
+
except Exception:
|
| 453 |
+
self.reply(500, {'ok': False, 'error': {'code': 'internal_error', 'message': 'Internal server error'}})
|
| 454 |
+
finally:
|
| 455 |
+
if acquired:
|
| 456 |
+
self.server.queries.release()
|
| 457 |
+
|
| 458 |
+
do_PUT = do_PATCH = do_DELETE = do_OPTIONS = reject_write
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
def create_key(auth_file, client_file, name):
|
| 462 |
+
import fcntl
|
| 463 |
+
if not re.fullmatch(r'[a-zA-Z0-9_.-]{1,64}', name):
|
| 464 |
+
raise ValueError('Invalid client name')
|
| 465 |
+
auth_file, client_file = Path(auth_file), Path(client_file)
|
| 466 |
+
auth_file.parent.mkdir(parents=True, exist_ok=True)
|
| 467 |
+
client_file.parent.mkdir(parents=True, exist_ok=True)
|
| 468 |
+
if client_file.exists():
|
| 469 |
+
raise ValueError('Client file already exists; refusing to overwrite')
|
| 470 |
+
with open(str(auth_file) + '.lock', 'a') as lock:
|
| 471 |
+
fcntl.flock(lock, fcntl.LOCK_EX)
|
| 472 |
+
document = json.loads(auth_file.read_text()) if auth_file.exists() else {'clients': {}}
|
| 473 |
+
if name in document['clients']:
|
| 474 |
+
raise ValueError('Client name already exists')
|
| 475 |
+
token = secrets.token_urlsafe(32)
|
| 476 |
+
document['clients'][name] = hashlib.sha256(token.encode()).hexdigest()
|
| 477 |
+
fd = os.open(client_file, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
| 478 |
+
with os.fdopen(fd, 'w') as out:
|
| 479 |
+
json.dump({'name': name, 'token': token}, out)
|
| 480 |
+
out.write('\n')
|
| 481 |
+
temporary = auth_file.with_name(auth_file.name + '.' + secrets.token_hex(8) + '.tmp')
|
| 482 |
+
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
| 483 |
+
with os.fdopen(fd, 'w') as out:
|
| 484 |
+
json.dump(document, out, indent=2)
|
| 485 |
+
out.write('\n')
|
| 486 |
+
os.replace(temporary, auth_file)
|
| 487 |
+
print(json.dumps({'created': name, 'client_file': str(client_file), 'auth_file': str(auth_file)}))
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
def main():
|
| 491 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 492 |
+
sub = parser.add_subparsers(dest='command', required=True)
|
| 493 |
+
key = sub.add_parser('create-key')
|
| 494 |
+
key.add_argument('--auth-file', required=True)
|
| 495 |
+
key.add_argument('--client-file', required=True)
|
| 496 |
+
key.add_argument('--name', required=True)
|
| 497 |
+
serve = sub.add_parser('serve')
|
| 498 |
+
serve.add_argument('--db', required=True)
|
| 499 |
+
serve.add_argument('--index', required=True)
|
| 500 |
+
access = serve.add_mutually_exclusive_group(required=True)
|
| 501 |
+
access.add_argument('--auth-file')
|
| 502 |
+
access.add_argument('--public', action='store_true', help='Allow unauthenticated read access to this library')
|
| 503 |
+
serve.add_argument('--host', default='127.0.0.1')
|
| 504 |
+
serve.add_argument('--port', type=int, default=8895)
|
| 505 |
+
args = parser.parse_args()
|
| 506 |
+
if args.command == 'create-key':
|
| 507 |
+
create_key(args.auth_file, args.client_file, args.name)
|
| 508 |
+
return
|
| 509 |
+
library = Library(args.db, args.index)
|
| 510 |
+
# Prepare shared counts before accepting the initial burst of scout reads.
|
| 511 |
+
library.domain_catalog()
|
| 512 |
+
server = Server((args.host, args.port), library, Credentials(args.auth_file) if args.auth_file else None)
|
| 513 |
+
print(f'ideaX read-only library API: http://{args.host}:{server.server_port}', flush=True)
|
| 514 |
+
try:
|
| 515 |
+
server.serve_forever()
|
| 516 |
+
except KeyboardInterrupt:
|
| 517 |
+
pass
|
| 518 |
+
finally:
|
| 519 |
+
server.server_close()
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
if __name__ == '__main__':
|
| 523 |
+
main()
|
api/library_api_agent_prompt.md
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
你可以使用 IdeaX / litgraph 研究知识库辅助完成用户的科研任务。它提供研究领域、领域下的 problems 和 insights,以及领域内论文及其结构化来源材料。请实际调用接口、阅读返回的证据,再回答用户。
|
| 2 |
+
|
| 3 |
+
服务根地址:BASE={{BASE_URL}}
|
| 4 |
+
接入说明:GET BASE/llms.txt
|
| 5 |
+
完整接口规范:GET BASE/openapi.json
|
| 6 |
+
{{AUTH_NOTE}}
|
| 7 |
+
|
| 8 |
+
先根据用户任务选择合适流程:查领域或论文时直接返回检索结果;分析研究问题时追溯来源;只有用户要求提出研究想法时才进行跨领域机制迁移,不要把普通查询扩展成完整研究项目。
|
| 9 |
+
|
| 10 |
+
对象的含义:domain 是研究范围、分类和统计容器;problem 是来源论文记录的限制、缺口或研究问题,不保证今天仍未解决;insight 是已有论文归纳的观察、机制、适用条件或失败模式,帮助理解已有方法和形成可检验的迁移假设。insight 本身不是你的新贡献。supporting_papers 是来源导航,成员可能分别支持不同主张,不能假定每篇论文支持整条归纳;paper 接口用于核对具体论文身份和可用材料。这些对象都不能单独证明新颖性。
|
| 11 |
+
|
| 12 |
+
1. 定位领域
|
| 13 |
+
调用 GET /api/v1/domains?q=<领域关键词>&limit=20,从返回结果中选择真实 domain_id。关键词需要 URL 编码;可先试英文,再试中文或同义词,不要猜测领域 ID。
|
| 14 |
+
调用 GET /api/v1/domains/{domain_id},读取领域描述和 counts。
|
| 15 |
+
|
| 16 |
+
2. 阅读该领域的问题、洞见和论文
|
| 17 |
+
GET /api/v1/domains/{domain_id}/problems?limit=20
|
| 18 |
+
GET /api/v1/domains/{domain_id}/insights?limit=20
|
| 19 |
+
GET /api/v1/domains/{domain_id}/papers?limit=20
|
| 20 |
+
insights/problems 加 q 可在领域内检索;papers 的 q 搜论文题名。省略 q 可分页浏览。领域论文列表包含该领域全部论文成员,并非只包含被条目引用的论文。
|
| 21 |
+
要优先阅读来源论文最多的条目,使用 GET /api/v1/domains/{domain_id}/insights?sort=paper_count&limit=20 或 /problems?sort=paper_count&limit=20。
|
| 22 |
+
将 limit 改为所需数量 N(每页 1–100 条)。paper_count 是 supporting_papers 中去重后的数字论文 ID 数;不是论文的外部被引次数,也不代表条目质量或新颖性。按数量降序,同数按条目 ID 升序。可以加 q 先过滤再排序;高支持量条目用于领域概览,仍需另外检索任务近邻和较新的低支持量条目。
|
| 23 |
+
领域探索建议:当你选定一个领域,想寻找研究方向或可迁移机制时,优先多读该领域的 insights,了解已有机制、适用前提与失败条件。建议先不加 q,调用 /api/v1/domains/{domain_id}/insights?sort=paper_count&limit=50,阅读前 50 条(不足 50 条则读实际返回的全部),再根据领域规模与上下文预算继续分页扩展。
|
| 24 |
+
阅读 statement、mechanism、scope 和 techniques,比较不同机制;对有启发的条目读取完整详情与来源论文,并结合该领域的 problems 寻找未解决的问题。随后按具体关键词补查支持论文较少的相关条目。保留已读条目 ID、数量、机制摘要与覆盖缺口,方便后续补读。
|
| 25 |
+
在 single-agent 全量探索模式中,目标领域的两类条目完整提供;想探索新领域时,鼓励先列出该领域全部 insights 和 problems。若配有 Python 客户端,使用 `library_client.py domain-context <domain_id> --output-dir <新目录>`,自动分页并核对数量,保存 entries.jsonl 与 manifest.json。随后连续分批阅读完整文件,避免终端输出截断;区分下载条目、实际已读条目和未覆盖部分。此客户端命令使用上述只读接口,不增加数据库写接口。
|
| 26 |
+
|
| 27 |
+
3. 按机制跨领域检索
|
| 28 |
+
GET /api/v1/search?q=<机制或问题关键词>&kind=insight&mode=all&limit=10
|
| 29 |
+
kind=problem 搜问题;unit=<domain_id> 限定领域;不设 unit 可查全库。fields=statement,mechanism 或 fields=techniques 可限定字段。
|
| 30 |
+
目标问题应与用户的研究方向有关,可迁移的 insight 可以来自任何领域。先用 mode=all,结果不足时改用 mode=any,并尝试中英文同义词。这是词法 BM25 检索,不是向量语义检索;分数越小排名越靠前,不代表质量或适用性置信度。
|
| 31 |
+
|
| 32 |
+
4. 核对条目和来源
|
| 33 |
+
GET /api/v1/entries/{entry_id} 读取完整条目、成员证据、机制、适用范围和 supporting_papers。
|
| 34 |
+
GET /api/v1/papers/{paper_id} 读取来源论文元数据、可用的结构化卡和领域归属。
|
| 35 |
+
GET /api/v1/papers/by-arxiv?id=<arxiv_id> 按 arXiv 查询。
|
| 36 |
+
POST /api/v1/papers/batch,JSON {"ids":[203336,172353]},一次最多 50 篇;检查 missing_ids。该 POST 只读取数据。
|
| 37 |
+
ID 必须来自实际返回值。数字 paper_id 与另一套谱系图里的 W 编号不是同一命名空间,不得互换。
|
| 38 |
+
|
| 39 |
+
5. 正确处理分页和错误
|
| 40 |
+
成功响应为 {"ok":true,"data":...},列表另有 page。领域列表和条目检索用 page.next_offset 作为 offset��普通条目浏览和领域论文列表用 page.next_after 原样作为 after。has_more=true 说明还有结果,不要把第一页数量当作全集数量。
|
| 41 |
+
sort=paper_count 始终使用 page.next_offset 翻页,不接受 after;需要超过 100 条时按 next_offset 继续取并累计至 N 条。
|
| 42 |
+
定点查询先取少量相关结果;领域探索按第 2 步广泛阅读 insights,并按任务需要翻页。只有用户要求完整清单时才必须遍历全部页面。
|
| 43 |
+
错误响应为 {"ok":false,"error":{"code":"...","message":"..."}}。400 时检查参数,404 时核对 ID,服务暂时不可用时有限重试并如实说明。无法调用时不得编造检索结果。这个部署使用临时公网域名,失效时需要最新地址。
|
| 44 |
+
|
| 45 |
+
6. 区分证据与推论
|
| 46 |
+
条目和论文卡是抽取、归并材料,不是论文 PDF 或完整原文。source_card_available=false 表示暂无结构化卡,仍可利用现有元数据。
|
| 47 |
+
来源论文支持的是其原有问题、机制或结论,不自动支持你的跨领域假设。说明哪些内容来自来源,哪些是你的推论,以及机制迁移的前提和可能失效条件。
|
| 48 |
+
检索不到不能证明新颖性;重要结论应进一步核对最接近的原始论文。未读原文时明确说明。该库含研究结果,未经日期截断和结果屏蔽,不应直接当作防泄漏 benchmark。
|
| 49 |
+
|
| 50 |
+
输出随用户任务调整:
|
| 51 |
+
- 检索或综述:给出相关领域、条目 ID、简明解释和来源论文,附可访问的 API 链接或论文链接。
|
| 52 |
+
- 研究想法:每个候选明确列出目标 problem、借用 insight、原有机制与适配步骤、区别于最接近工作的贡献、可证伪预测、最小对照实验和主要失败条件。提出时就检索领域近邻与跨领域机制等价工作,尽可能读最近邻的原文方法和公式。尝试用变量替换、限制特例将候选归约成前作,并写明剔除已知部分后的剩余贡献;被覆盖则撤回或重写。
|
| 53 |
+
- IdeaX 卡片需保存 source_entry_ids(problems/insights 两个数组)、entry_usage(每项 id、kind、role、use)和 litgraph_queries(每项 endpoint 及实际参数、purpose、result_ids、read_depth)。每个来源逐项说明如何影响问题、机制、边界、反例筛选或实验;不得事后补造影响过程。辩论重新打开争议条目和最近邻论文,作者将成立的修订写回原卡;最终 selector 仅选择已有 card ID。
|
| 54 |
+
- 每个想法必须有 Previous work,格式为 `《数字 paper_id》完整标题`,附 `BASE/api/v1/papers/<数字 paper_id>`。逐篇通过 API 核对编号与标题,写出阅读深度(fulltext / abstract / source_card / metadata)、具体原文位置、重合点和区别。未入库的最近邻另列原文链接及查找记录,不编造编号也不省略。记录实际检索词、覆盖缺口和未排除的等价风险;API 身份校验不能证明新颖性。
|
| 55 |
+
- 检索无结果或证据不足:报告尝试过的关键词、覆盖范围和缺口,不补造引用。
|
| 56 |
+
|
| 57 |
+
知识蒸馏查询示例(示例 ID 不限制用户选择其他方向):
|
| 58 |
+
GET BASE/api/v1/domains?q=distillation&limit=20
|
| 59 |
+
GET BASE/api/v1/domains/knowledge-distillation
|
| 60 |
+
GET BASE/api/v1/domains/knowledge-distillation/problems?limit=10
|
| 61 |
+
GET BASE/api/v1/domains/knowledge-distillation/insights?limit=10
|
| 62 |
+
GET BASE/api/v1/domains/knowledge-distillation/insights?sort=paper_count&limit=20
|
| 63 |
+
GET BASE/api/v1/domains/knowledge-distillation/problems?sort=paper_count&limit=20
|
| 64 |
+
GET BASE/api/v1/domains/knowledge-distillation/papers?limit=10
|
| 65 |
+
GET BASE/api/v1/search?q=control%20variate&kind=insight&mode=any&limit=10
|
| 66 |
+
|
| 67 |
+
用户的具体任务:沿用当前对话中用户提出的问题、研究方向和约束。
|
api/library_api_docs.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Machine-readable discovery for the ideaX library API."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def agent_prompt(base_url=None, requires_key=False):
|
| 6 |
+
base_url = base_url or '本说明所在服务的根地址(从 /llms.txt URL 去掉 /llms.txt)'
|
| 7 |
+
auth = ('所有 /api/v1 请求需要 Authorization: Bearer <API_KEY>;使用服务所有者提供的凭据。'
|
| 8 |
+
if requires_key else '当前公开可读,无需 API key。')
|
| 9 |
+
auth += ' 所有接口只读,不接受任意 SQL、创建、更新或删除;本服务不提供执行研究生成的 HTTP 接口。'
|
| 10 |
+
template = Path(__file__).with_name('library_api_agent_prompt.md').read_text(encoding='utf-8')
|
| 11 |
+
return template.replace('{{BASE_URL}}', base_url).replace('{{AUTH_NOTE}}', auth)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def llms_text(requires_key=False):
|
| 15 |
+
auth = 'All /api/v1 routes require Authorization: Bearer <API_KEY>.\n' if requires_key else 'This instance permits public, read-only access.\n'
|
| 16 |
+
return '# Copyable prompt for agents / 可直接交给其他 agent 的提示词\n\n' + agent_prompt(requires_key=requires_key) + '''
|
| 17 |
+
|
| 18 |
+
# ideaX / litgraph research domains API
|
| 19 |
+
|
| 20 |
+
Read /openapi.json for parameter and response schemas.
|
| 21 |
+
''' + auth + '''
|
| 22 |
+
1. GET /api/v1/domains?q=distillation&limit=20 finds research domains by name or ID.
|
| 23 |
+
Omit q to browse all domains; use page.next_offset as offset for the next page.
|
| 24 |
+
2. GET /api/v1/domains/knowledge-distillation returns domain details and counts.
|
| 25 |
+
3. GET /api/v1/domains/knowledge-distillation/insights?limit=20
|
| 26 |
+
GET /api/v1/domains/knowledge-distillation/problems?limit=20
|
| 27 |
+
list the domain's insights and problems. Add q for lexical search within the domain.
|
| 28 |
+
Add sort=paper_count&limit=N for the N entries with the most distinct supporting
|
| 29 |
+
papers. paper_count is the deduplicated size of supporting_papers, NOT external
|
| 30 |
+
citation counts or a quality/novelty score. Ties use entry ID ascending.
|
| 31 |
+
q may filter matches before ranking. Use page.next_offset for ranked pagination;
|
| 32 |
+
after is not accepted with sort=paper_count. Each page supports 1–100 entries.
|
| 33 |
+
When exploring a chosen domain, read its insights broadly: start without q
|
| 34 |
+
with sort=paper_count&limit=50 (or all available if fewer), then paginate as
|
| 35 |
+
domain size and context budget allow. Compare mechanisms, assumptions, and
|
| 36 |
+
failure conditions; inspect promising entries and source papers, and connect
|
| 37 |
+
them to the domain's problems. Follow with targeted searches for relevant
|
| 38 |
+
lower-support entries. Keep entry IDs, reading counts, and coverage gaps.
|
| 39 |
+
4. GET /api/v1/domains/knowledge-distillation/papers?limit=20
|
| 40 |
+
lists ALL papers assigned to the domain, including papers without extracted
|
| 41 |
+
source cards. source_card_available=false distinguishes those records.
|
| 42 |
+
Use page.next_after as after for subsequent pages. Optional q searches titles.
|
| 43 |
+
5. GET /api/v1/search?q=on-policy%20distillation&kind=problem&mode=all&limit=10
|
| 44 |
+
searches problem statements, mechanisms, scopes, and technique names.
|
| 45 |
+
kind=insight searches transferable insights. Omit kind to search both.
|
| 46 |
+
fields=techniques searches named techniques; fields=statement,mechanism narrows
|
| 47 |
+
the searched fields. Use mode=any for broader recall or Chinese search terms.
|
| 48 |
+
unit=knowledge-distillation restricts the research domain.
|
| 49 |
+
6. GET /api/v1/entries/{entry_id} returns the complete entry, member evidence,
|
| 50 |
+
source paper IDs, and technique names. Read it before applying a mechanism.
|
| 51 |
+
7. GET /api/v1/papers/{paper_id} returns paper metadata and its structured source
|
| 52 |
+
card when available, plus the paper's domain memberships.
|
| 53 |
+
These numeric IDs are NOT the W-prefixed IDs used in the separate lineage DB.
|
| 54 |
+
8. GET /api/v1/papers/by-arxiv?id=2605.07865 returns matching papers.
|
| 55 |
+
9. POST /api/v1/papers/batch with JSON {"ids":[203336,172353]} reads up to 50
|
| 56 |
+
source cards. This POST only reads data; missing_ids lists absent IDs.
|
| 57 |
+
10. GET /api/v1/entries?kind=insight&limit=100 browses entries. Continue using
|
| 58 |
+
page.next_after as after. Search and paper_count-ranked pages use page.next_offset as offset.
|
| 59 |
+
11. GET /api/v1/stats reports the snapshot counts. GET /health is a liveness check.
|
| 60 |
+
|
| 61 |
+
Responses use {"ok":true,"data":...}; list/search responses also contain page.
|
| 62 |
+
Errors use {"ok":false,"error":{"code":"...","message":"..."}}.
|
| 63 |
+
Search uses lexical field-specific BM25, with Chinese bigram tokenization.
|
| 64 |
+
The score is a ranking value (lower ranks first), not confidence or applicability.
|
| 65 |
+
This API does not provide embedding/vector search, arbitrary SQL, or mutations.
|
| 66 |
+
|
| 67 |
+
Evidence limits:
|
| 68 |
+
- Entries and source cards are extracted/merged research materials, not paper PDFs
|
| 69 |
+
or full text. Source coverage and extraction quality vary; inspect evidence.
|
| 70 |
+
- Supporting papers support the source entry, not a new hypothesis you derive.
|
| 71 |
+
- Results have NOT been masked. Do not use this live corpus as a date-safe or
|
| 72 |
+
result-blind benchmark without a separately prepared snapshot.
|
| 73 |
+
- A failed search does not establish novelty. Search both Chinese and English,
|
| 74 |
+
inspect source cards, and verify the closest original papers independently.
|
| 75 |
+
'''
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def openapi(requires_key=False):
|
| 79 |
+
success = {'description': 'Read succeeded', 'content': {'application/json': {'schema': {'$ref': '#/components/schemas/Envelope'}}}}
|
| 80 |
+
error = {'description': 'Request rejected or resource unavailable', 'content': {'application/json': {'schema': {'$ref': '#/components/schemas/Error'}}}}
|
| 81 |
+
|
| 82 |
+
def operation(summary, parameters=None):
|
| 83 |
+
value = {'summary': summary, 'responses': {'200': success, '400': error, '404': error, '503': error}}
|
| 84 |
+
if parameters:
|
| 85 |
+
value['parameters'] = parameters
|
| 86 |
+
if requires_key:
|
| 87 |
+
value['security'] = [{'BearerAuth': []}]
|
| 88 |
+
value['responses']['401'] = error
|
| 89 |
+
return value
|
| 90 |
+
|
| 91 |
+
def query(name, schema, description='', required=False):
|
| 92 |
+
return {'name': name, 'in': 'query', 'required': required, 'schema': schema, 'description': description}
|
| 93 |
+
|
| 94 |
+
parameters = [
|
| 95 |
+
query('q', {'type': 'string', 'minLength': 1, 'maxLength': 500}, 'Lexical query; Chinese or English.'),
|
| 96 |
+
query('kind', {'type': 'string', 'enum': ['problem', 'insight']}),
|
| 97 |
+
query('unit', {'type': 'string'}, 'Research domain ID returned by /units.'),
|
| 98 |
+
query('fields', {'type': 'string', 'default': 'statement,mechanism,scope,techniques'}, 'Comma-separated subset of statement,mechanism,scope,techniques.'),
|
| 99 |
+
query('mode', {'type': 'string', 'enum': ['all', 'any'], 'default': 'all'}, 'Require every token or match any token.'),
|
| 100 |
+
query('sort', {'type': 'string', 'enum': ['id', 'relevance', 'paper_count']},
|
| 101 |
+
'Default: relevance with q, otherwise id. paper_count sorts distinct supporting-paper count descending, then entry ID ascending; not external citations. q filters before sorting. relevance requires q.'),
|
| 102 |
+
query('limit', {'type': 'integer', 'minimum': 1, 'maximum': 100, 'default': 20}),
|
| 103 |
+
query('offset', {'type': 'integer', 'minimum': 0, 'maximum': 10000, 'default': 0}, 'Search or paper_count pagination; use page.next_offset. Prefer after for ID-ordered browsing.'),
|
| 104 |
+
query('after', {'type': 'string'}, 'ID-ordered browsing only; cannot combine with q, paper_count sorting, or nonzero offset.'),
|
| 105 |
+
]
|
| 106 |
+
search_parameters = [dict(p, required=True) if p['name'] == 'q' else p for p in parameters if p['name'] != 'after']
|
| 107 |
+
batch = operation('Read up to 50 source paper cards; no database writes')
|
| 108 |
+
batch['x-read-only'] = True
|
| 109 |
+
batch_schema = {
|
| 110 |
+
'type': 'object', 'required': ['ids'], 'additionalProperties': False,
|
| 111 |
+
'properties': {'ids': {'type': 'array', 'minItems': 1, 'maxItems': 50,
|
| 112 |
+
'items': {'oneOf': [{'type': 'integer', 'minimum': 0}, {'type': 'string', 'pattern': '^[0-9]{1,20}$'}]}}}}
|
| 113 |
+
batch['requestBody'] = {'required': True, 'content': {'application/json': {'schema': batch_schema}}}
|
| 114 |
+
paths = {
|
| 115 |
+
'/health': {'get': {'summary': 'Liveness', 'responses': {'200': success}}},
|
| 116 |
+
'/api/v1/stats': {'get': operation('Snapshot counts')},
|
| 117 |
+
'/api/v1/units': {'get': operation('Research domains and per-kind counts')},
|
| 118 |
+
'/api/v1/domains': {'get': operation('Browse or search litgraph research domains', [
|
| 119 |
+
query('q', {'type': 'string'}, 'Matches domain name and ID.'),
|
| 120 |
+
query('limit', {'type': 'integer', 'minimum': 1, 'maximum': 100, 'default': 50}),
|
| 121 |
+
query('offset', {'type': 'integer', 'minimum': 0, 'maximum': 10000, 'default': 0})])},
|
| 122 |
+
'/api/v1/search': {'get': operation('Search problem, insight, and technique fields', search_parameters)},
|
| 123 |
+
'/api/v1/entries': {'get': operation('Browse or search entries', parameters)},
|
| 124 |
+
'/api/v1/entries/{entry_id}': {'get': operation('Complete entry and provenance', [
|
| 125 |
+
{'name': 'entry_id', 'in': 'path', 'required': True, 'schema': {'type': 'string'}, 'example': 'knowledge-distillation-P0062'}])},
|
| 126 |
+
'/api/v1/papers/{paper_id}': {'get': operation('Structured source paper card', [
|
| 127 |
+
{'name': 'paper_id', 'in': 'path', 'required': True, 'schema': {'type': 'string', 'pattern': '^[0-9]{1,20}$'}, 'example': '203336'}])},
|
| 128 |
+
'/api/v1/papers/by-arxiv': {'get': operation('Source cards matching an arXiv ID', [
|
| 129 |
+
query('id', {'type': 'string'}, 'Version suffixes and arXiv URLs are accepted.', True)])},
|
| 130 |
+
'/api/v1/papers/batch': {'post': batch},
|
| 131 |
+
}
|
| 132 |
+
domain_param = {'name': 'domain_id', 'in': 'path', 'required': True, 'schema': {'type': 'string'}, 'example': 'knowledge-distillation'}
|
| 133 |
+
paths['/api/v1/domains/{domain_id}'] = {'get': operation('Domain details and counts', [domain_param])}
|
| 134 |
+
for resource in ('insights', 'problems'):
|
| 135 |
+
paths['/api/v1/domains/{domain_id}/' + resource] = {'get': operation(
|
| 136 |
+
'Browse or search this domain\'s ' + resource,
|
| 137 |
+
[domain_param] + [p for p in parameters if p['name'] not in ('unit', 'kind')])}
|
| 138 |
+
paths['/api/v1/domains/{domain_id}/papers'] = {'get': operation('All papers assigned to this domain, including metadata-only papers', [
|
| 139 |
+
domain_param, query('q', {'type': 'string'}, 'Search paper titles.'),
|
| 140 |
+
query('limit', {'type': 'integer', 'minimum': 1, 'maximum': 100, 'default': 20}),
|
| 141 |
+
query('after', {'type': 'string'}, 'Paper ID returned as page.next_after.')])}
|
| 142 |
+
for path, item in paths.items():
|
| 143 |
+
if path in ('/api/v1/search', '/api/v1/entries', '/api/v1/entries/{entry_id}') or path.endswith(('/insights', '/problems')):
|
| 144 |
+
data_schema = {'$ref': '#/components/schemas/Entry'}
|
| 145 |
+
if path != '/api/v1/entries/{entry_id}':
|
| 146 |
+
data_schema = {'type': 'array', 'items': data_schema}
|
| 147 |
+
item['get']['responses']['200'] = {'description': 'Entries include paper_count (distinct supporting papers)',
|
| 148 |
+
'content': {'application/json': {'schema': {'allOf': [
|
| 149 |
+
{'$ref': '#/components/schemas/Envelope'},
|
| 150 |
+
{'type': 'object', 'properties': {'data': data_schema}}]}}}}
|
| 151 |
+
return {
|
| 152 |
+
'openapi': '3.0.3',
|
| 153 |
+
'info': {'title': 'ideaX / litgraph Read-only Domains API', 'version': '1.1.0',
|
| 154 |
+
'description': 'Research domains, their insights/problems, all member papers, and source cards. Read /llms.txt for evidence limits. Results are not masked.'},
|
| 155 |
+
'paths': paths,
|
| 156 |
+
'components': {
|
| 157 |
+
'securitySchemes': {'BearerAuth': {'type': 'http', 'scheme': 'bearer'}},
|
| 158 |
+
'schemas': {
|
| 159 |
+
'Entry': {'type': 'object', 'required': ['id', 'paper_count'], 'properties': {
|
| 160 |
+
'id': {'type': 'string'}, 'kind': {'type': 'string', 'enum': ['insight', 'problem']},
|
| 161 |
+
'statement': {'type': 'string', 'nullable': True},
|
| 162 |
+
'supporting_papers': {'type': 'array', 'nullable': True, 'items': {
|
| 163 |
+
'oneOf': [{'type': 'integer'}, {'type': 'string'}]}},
|
| 164 |
+
'paper_count': {'type': 'integer', 'minimum': 0,
|
| 165 |
+
'description': 'Distinct numeric IDs in supporting_papers. Missing/null/empty lists count as 0. Not external citation count, quality, or novelty.'}}},
|
| 166 |
+
'Envelope': {'type': 'object', 'required': ['ok', 'data'], 'properties': {
|
| 167 |
+
'ok': {'type': 'boolean', 'enum': [True]}, 'data': {}, 'page': {
|
| 168 |
+
'type': 'object', 'properties': {'limit': {'type': 'integer'}, 'count': {'type': 'integer'},
|
| 169 |
+
'has_more': {'type': 'boolean'}, 'sort': {'type': 'string', 'enum': ['id', 'relevance', 'paper_count']},
|
| 170 |
+
'next_offset': {'type': 'integer', 'nullable': True},
|
| 171 |
+
'next_after': {'type': 'string', 'nullable': True}}}}},
|
| 172 |
+
'Error': {'type': 'object', 'required': ['ok', 'error'], 'properties': {
|
| 173 |
+
'ok': {'type': 'boolean', 'enum': [False]}, 'error': {'type': 'object', 'required': ['code', 'message'],
|
| 174 |
+
'properties': {'code': {'type': 'string'}, 'message': {'type': 'string'}}}}},
|
| 175 |
+
},
|
| 176 |
+
},
|
| 177 |
+
}
|
api/library_api_index.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build a separate field-search/arXiv index without changing library.db."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import re
|
| 7 |
+
import sqlite3
|
| 8 |
+
import time
|
| 9 |
+
|
| 10 |
+
from library_query import tokens
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
FIELDS = ('statement', 'mechanism', 'scope', 'techniques')
|
| 14 |
+
INDEX_VERSION = '3'
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def supporting_paper_count(entry):
|
| 18 |
+
"""Count distinct numeric source-paper IDs, not external citation counts."""
|
| 19 |
+
return len({int(value) for value in (entry.get('supporting_papers') or [])
|
| 20 |
+
if not isinstance(value, bool) and re.fullmatch(r'[0-9]{1,20}', str(value))})
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def arxiv_id(value):
|
| 24 |
+
match = re.search(r'(\d{4}\.\d{4,5}|[a-z][a-z.\-]+/\d{7})(?:v\d+)?', str(value or ''), re.I)
|
| 25 |
+
return match.group(1).lower() if match else None
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def fingerprint(path):
|
| 29 |
+
stat = Path(path).stat()
|
| 30 |
+
return {'size': stat.st_size, 'mtime_ns': stat.st_mtime_ns}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def build(database, output, domains_file=None, papers_file=None):
|
| 34 |
+
source, output = Path(database).resolve(strict=True), Path(output).resolve()
|
| 35 |
+
if source == output:
|
| 36 |
+
raise ValueError('Search index must be a separate file')
|
| 37 |
+
output.parent.mkdir(parents=True, exist_ok=True)
|
| 38 |
+
temp = output.with_name(output.name + f'.{os.getpid()}.building')
|
| 39 |
+
before = fingerprint(source)
|
| 40 |
+
domains_file = Path(domains_file) if domains_file else source.parent / 'domains.json'
|
| 41 |
+
papers_file = Path(papers_file) if papers_file else source.parent.parent / 'papers.jsonl'
|
| 42 |
+
catalog = json.loads(domains_file.read_text())['domains'] if domains_file.exists() else None
|
| 43 |
+
start = time.monotonic()
|
| 44 |
+
with sqlite3.connect(source.as_uri() + '?mode=ro', uri=True) as src, sqlite3.connect(temp) as dst:
|
| 45 |
+
dst.executescript('''
|
| 46 |
+
CREATE TABLE metadata(key TEXT PRIMARY KEY, value TEXT);
|
| 47 |
+
CREATE TABLE entries(id TEXT PRIMARY KEY, kind TEXT, unit TEXT, paper_count INTEGER NOT NULL);
|
| 48 |
+
CREATE INDEX entries_kind_unit ON entries(kind,unit);
|
| 49 |
+
CREATE INDEX entries_domain_paper_count ON entries(unit,kind,paper_count DESC,id);
|
| 50 |
+
CREATE INDEX entries_paper_count ON entries(paper_count DESC,id);
|
| 51 |
+
CREATE VIRTUAL TABLE entry_fts USING fts5(id UNINDEXED, statement, mechanism, scope, techniques);
|
| 52 |
+
CREATE TABLE papers(id TEXT PRIMARY KEY, arxiv TEXT, data TEXT, has_source_card INTEGER NOT NULL);
|
| 53 |
+
CREATE INDEX papers_arxiv ON papers(arxiv);
|
| 54 |
+
CREATE TABLE domains(id TEXT PRIMARY KEY, data TEXT);
|
| 55 |
+
CREATE TABLE domain_papers(domain_id TEXT, paper_id TEXT, PRIMARY KEY(domain_id,paper_id));
|
| 56 |
+
CREATE INDEX domain_papers_paper ON domain_papers(paper_id);
|
| 57 |
+
''')
|
| 58 |
+
count = 0
|
| 59 |
+
inferred_domains = {}
|
| 60 |
+
for identifier, kind, unit, data in src.execute('SELECT id,kind,unit,data FROM entries'):
|
| 61 |
+
entry = json.loads(data)
|
| 62 |
+
values = []
|
| 63 |
+
for field in FIELDS:
|
| 64 |
+
value = entry.get(field, '')
|
| 65 |
+
if field == 'techniques' and isinstance(value, list):
|
| 66 |
+
value = ' '.join(x.get('name', '') if isinstance(x, dict) else str(x) for x in value)
|
| 67 |
+
if entry.get('summary_policy') == 'first_three_eligible_source_card_excerpts':
|
| 68 |
+
member_field = 'scope_tag' if field == 'scope' else field
|
| 69 |
+
member_values = [m.get(member_field) or '' for m in entry.get('members', [])]
|
| 70 |
+
value = str(value or '') + ' ' + ' '.join(
|
| 71 |
+
json.dumps(v, ensure_ascii=False) if not isinstance(v, str) else v for v in member_values)
|
| 72 |
+
values.append(' '.join(tokens(str(value or ''))))
|
| 73 |
+
dst.execute('INSERT INTO entries VALUES(?,?,?,?)', (identifier, kind, unit, supporting_paper_count(entry)))
|
| 74 |
+
dst.execute('INSERT INTO entry_fts VALUES(?,?,?,?,?)', (identifier, *values))
|
| 75 |
+
inferred = inferred_domains.setdefault(unit, {'id': unit, 'name': entry.get('unit_name', unit), 'papers': set()})
|
| 76 |
+
inferred['papers'].update(str(x) for x in (entry.get('supporting_papers') or []))
|
| 77 |
+
count += 1
|
| 78 |
+
catalog = catalog if catalog is not None else list(inferred_domains.values())
|
| 79 |
+
wanted = set()
|
| 80 |
+
for domain in catalog:
|
| 81 |
+
info = {k: domain[k] for k in ('id', 'name', 'lines', 'directions') if k in domain}
|
| 82 |
+
dst.execute('INSERT INTO domains VALUES(?,?)', (domain['id'], json.dumps(info, ensure_ascii=False)))
|
| 83 |
+
for pid in set(str(x) for x in domain.get('papers', [])):
|
| 84 |
+
wanted.add(pid)
|
| 85 |
+
dst.execute('INSERT INTO domain_papers VALUES(?,?)', (domain['id'], pid))
|
| 86 |
+
paper_count = 0
|
| 87 |
+
for identifier, data in src.execute('SELECT id,data FROM papers'):
|
| 88 |
+
entry = json.loads(data)
|
| 89 |
+
metadata = {k: entry.get(k) for k in ('title', 'arxiv', 'year', 'venue')}
|
| 90 |
+
metadata.update(id=identifier, paper_id=int(identifier), source_card_available=True)
|
| 91 |
+
dst.execute('INSERT INTO papers VALUES(?,?,?,1)', (identifier, arxiv_id(entry.get('arxiv')), json.dumps(metadata, ensure_ascii=False)))
|
| 92 |
+
paper_count += 1
|
| 93 |
+
if papers_file.exists():
|
| 94 |
+
source_ids = {row[0] for row in dst.execute('SELECT id FROM papers')}
|
| 95 |
+
with papers_file.open() as stream:
|
| 96 |
+
for line in stream:
|
| 97 |
+
entry = json.loads(line)
|
| 98 |
+
identifier = str(entry['id'])
|
| 99 |
+
if identifier not in wanted:
|
| 100 |
+
continue
|
| 101 |
+
metadata = {k: entry.get(k) for k in ('title', 'arxiv', 'year', 'abstract')}
|
| 102 |
+
metadata.update(id=identifier, paper_id=int(identifier), venue=entry.get('conference'), source_card_available=identifier in source_ids)
|
| 103 |
+
dst.execute('INSERT INTO papers VALUES(?,?,?,0) ON CONFLICT(id) DO UPDATE SET arxiv=excluded.arxiv,data=excluded.data',
|
| 104 |
+
(identifier, arxiv_id(entry.get('arxiv')), json.dumps(metadata, ensure_ascii=False)))
|
| 105 |
+
# Keep every declared domain member visible, even if the upstream metadata is missing.
|
| 106 |
+
for (identifier,) in dst.execute('SELECT DISTINCT paper_id FROM domain_papers WHERE paper_id NOT IN (SELECT id FROM papers)').fetchall():
|
| 107 |
+
metadata = {'id': identifier, 'paper_id': int(identifier), 'source_card_available': False, 'metadata_available': False}
|
| 108 |
+
dst.execute('INSERT INTO papers VALUES(?,NULL,?,0)', (identifier, json.dumps(metadata)))
|
| 109 |
+
dst.execute('INSERT INTO metadata VALUES(?,?)', ('source', json.dumps(before)))
|
| 110 |
+
dst.execute('INSERT INTO metadata VALUES(?,?)', ('version', INDEX_VERSION))
|
| 111 |
+
dst.commit()
|
| 112 |
+
if before != fingerprint(source):
|
| 113 |
+
temp.unlink()
|
| 114 |
+
raise RuntimeError('Library changed during indexing; retry against a stable snapshot')
|
| 115 |
+
os.replace(temp, output)
|
| 116 |
+
return {'entries': count, 'source_cards': paper_count, 'domain_papers': len(wanted), 'domains': len(catalog),
|
| 117 |
+
'seconds': round(time.monotonic() - start, 2), 'index': str(output)}
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
if __name__ == '__main__':
|
| 121 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 122 |
+
parser.add_argument('--db', required=True)
|
| 123 |
+
parser.add_argument('--output', required=True)
|
| 124 |
+
parser.add_argument('--domains')
|
| 125 |
+
parser.add_argument('--papers')
|
| 126 |
+
args = parser.parse_args()
|
| 127 |
+
print(json.dumps(build(args.db, args.output, args.domains, args.papers), ensure_ascii=False))
|
api/library_query.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Search and inspect the domain problem/insight snapshot used by ideaX.
|
| 2 |
+
|
| 3 |
+
library_query.py build --source <insight_lib> --db <library.db>
|
| 4 |
+
library_query.py search <words> [--kind problem|insight] [--unit <id>] [-k 12]
|
| 5 |
+
library_query.py show <entry-id> | paper <numeric-paper-id>
|
| 6 |
+
|
| 7 |
+
Entry IDs belong to insight_lib; numeric paper IDs are NOT lit.db W IDs.
|
| 8 |
+
"""
|
| 9 |
+
import argparse
|
| 10 |
+
import json
|
| 11 |
+
import os
|
| 12 |
+
import re
|
| 13 |
+
import sqlite3
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def tokens(text):
|
| 18 |
+
parts = re.findall(r'[a-z0-9]+|[\u4e00-\u9fff]+', text.lower())
|
| 19 |
+
return list(dict.fromkeys(t for p in parts for t in
|
| 20 |
+
([p] if not re.search(r'[\u4e00-\u9fff]', p) else
|
| 21 |
+
[p[i:i + 2] for i in range(max(1, len(p) - 1))])))
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def build(source, output):
|
| 25 |
+
source, output = Path(source), Path(output)
|
| 26 |
+
output.parent.mkdir(parents=True, exist_ok=True)
|
| 27 |
+
temp = output.with_suffix('.building.db')
|
| 28 |
+
if temp.exists():
|
| 29 |
+
temp.unlink()
|
| 30 |
+
con = sqlite3.connect(temp)
|
| 31 |
+
con.executescript('''
|
| 32 |
+
create table entries(id text primary key, kind text, unit text, data text);
|
| 33 |
+
create virtual table search using fts5(id UNINDEXED, words);
|
| 34 |
+
create table papers(id text primary key, data text);
|
| 35 |
+
create index entries_kind_unit on entries(kind, unit);
|
| 36 |
+
''')
|
| 37 |
+
names = {d['id']: d['name'] for d in json.loads((source / 'domains.json').read_text())['domains']}
|
| 38 |
+
paper_ids = set()
|
| 39 |
+
count = 0
|
| 40 |
+
for unit in sorted((source / 'domains').iterdir()):
|
| 41 |
+
if not unit.is_dir():
|
| 42 |
+
continue
|
| 43 |
+
for kind in ('problem', 'insight'):
|
| 44 |
+
path = unit / (kind + '.json')
|
| 45 |
+
if not path.exists():
|
| 46 |
+
continue
|
| 47 |
+
for entry in json.loads(path.read_text()).get('entries', []):
|
| 48 |
+
entry = dict(entry, unit=unit.name, unit_name=names.get(unit.name, unit.name), kind=kind)
|
| 49 |
+
text = ' '.join(str(entry.get(k) or '') for k in ('unit', 'unit_name', 'statement', 'mechanism', 'scope', 'techniques'))
|
| 50 |
+
con.execute('insert into entries values(?,?,?,?)',
|
| 51 |
+
(entry['id'], kind, unit.name, json.dumps(entry, ensure_ascii=False)))
|
| 52 |
+
con.execute('insert into search values(?,?)', (entry['id'], ' '.join(tokens(text))))
|
| 53 |
+
for e in [entry] + entry.get('members', []):
|
| 54 |
+
paper_ids.update(str(p) for p in e.get('supporting_papers', []))
|
| 55 |
+
count += 1
|
| 56 |
+
for pid in sorted(paper_ids):
|
| 57 |
+
path = source / 'cards' / (pid + '.json')
|
| 58 |
+
if path.exists():
|
| 59 |
+
card = json.loads(path.read_text())
|
| 60 |
+
# Keep source evidence and metadata; generation traces are unnecessary.
|
| 61 |
+
card = {k: v for k, v in card.items() if k not in ('raw', 'usage', 'response', 'prompt')}
|
| 62 |
+
con.execute('insert into papers values(?,?)', (pid, json.dumps(card, ensure_ascii=False)))
|
| 63 |
+
con.commit()
|
| 64 |
+
papers = con.execute('select count(*) from papers').fetchone()[0]
|
| 65 |
+
con.close()
|
| 66 |
+
os.replace(temp, output)
|
| 67 |
+
return {'entries': count, 'papers': papers, 'db': str(output)}
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def main():
|
| 71 |
+
ap = argparse.ArgumentParser(description=__doc__)
|
| 72 |
+
ap.add_argument('--db', default=os.environ.get('LITGRAPH_LIBRARY_DB', '/work/library.db'))
|
| 73 |
+
sub = ap.add_subparsers(dest='cmd', required=True)
|
| 74 |
+
b = sub.add_parser('build')
|
| 75 |
+
b.add_argument('--source', required=True)
|
| 76 |
+
s = sub.add_parser('search')
|
| 77 |
+
s.add_argument('query', nargs='+')
|
| 78 |
+
s.add_argument('--kind', choices=['problem', 'insight'])
|
| 79 |
+
s.add_argument('--unit')
|
| 80 |
+
s.add_argument('-k', type=int, default=12)
|
| 81 |
+
for name in ('show', 'paper'):
|
| 82 |
+
sub.add_parser(name).add_argument('id')
|
| 83 |
+
args = ap.parse_args()
|
| 84 |
+
if args.cmd == 'build':
|
| 85 |
+
print(json.dumps(build(args.source, args.db), ensure_ascii=False))
|
| 86 |
+
return
|
| 87 |
+
from library_client import LibraryClient, LibraryAPIError, run_config
|
| 88 |
+
# A run opts into HTTP explicitly; reconstruction and older runs stay on their snapshot.
|
| 89 |
+
if run_config().get('base_url'):
|
| 90 |
+
try:
|
| 91 |
+
client = LibraryClient()
|
| 92 |
+
if args.cmd in ('show', 'paper'):
|
| 93 |
+
data = client.entry(args.id) if args.cmd == 'show' else client.paper(args.id)
|
| 94 |
+
print(json.dumps(data, ensure_ascii=False, indent=2))
|
| 95 |
+
else:
|
| 96 |
+
result = client.request('/api/v1/search', dict(q=' '.join(args.query), kind=args.kind,
|
| 97 |
+
unit=args.unit, limit=args.k, mode='any'))
|
| 98 |
+
# Preserve page metadata rather than silently dropping unfetched results.
|
| 99 |
+
print(json.dumps(result, ensure_ascii=False, indent=2))
|
| 100 |
+
return
|
| 101 |
+
except LibraryAPIError as exc:
|
| 102 |
+
raise SystemExit(str(exc)) from exc
|
| 103 |
+
con = sqlite3.connect('file:' + str(Path(args.db).absolute()) + '?mode=ro', uri=True)
|
| 104 |
+
if args.cmd in ('show', 'paper'):
|
| 105 |
+
table = 'entries' if args.cmd == 'show' else 'papers'
|
| 106 |
+
row = con.execute(f'select data from {table} where id=?', (args.id,)).fetchone()
|
| 107 |
+
if not row:
|
| 108 |
+
raise SystemExit(f'No {args.cmd} ID {args.id}')
|
| 109 |
+
print(json.dumps(json.loads(row[0]), ensure_ascii=False, indent=2))
|
| 110 |
+
else:
|
| 111 |
+
terms = tokens(' '.join(args.query))
|
| 112 |
+
if not terms:
|
| 113 |
+
raise SystemExit('Search needs a nonempty term')
|
| 114 |
+
sql = 'select e.data from search join entries e on e.id=search.id where search match ?'
|
| 115 |
+
params = [' OR '.join('"' + t + '"' for t in terms)]
|
| 116 |
+
for k in ('kind', 'unit'):
|
| 117 |
+
if getattr(args, k):
|
| 118 |
+
sql += f' and e.{k}=?'
|
| 119 |
+
params.append(getattr(args, k))
|
| 120 |
+
sql += ' order by bm25(search) limit ?'
|
| 121 |
+
params.append(args.k)
|
| 122 |
+
for (data,) in con.execute(sql, params):
|
| 123 |
+
d = json.loads(data)
|
| 124 |
+
print(json.dumps({k: d.get(k) for k in ('id', 'kind', 'unit', 'unit_name', 'statement', 'mechanism', 'scope', 'supporting_papers')}, ensure_ascii=False))
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
if __name__ == '__main__':
|
| 128 |
+
main()
|
data/domain_papers.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:70b7b44dad6396cebb6cb341145012a2ccda6bb0090a76d15a760b520cd1c3e5
|
| 3 |
+
size 1103057
|
data/domains.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d05559df3c7a6e814bf70a36500283928bc87a42edf7bf51a676286cd28b29e6
|
| 3 |
+
size 903588
|
data/insights.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:82d22c7b8919c9122f52d403bcc9bb856fc8ef9b6c800cb54f1d9cbddd42f2fe
|
| 3 |
+
size 103279130
|
data/papers.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:62101a0f4a20e091d59f8ed4233064bd6a3f169a075df9d70e2f1f8fda27fae9
|
| 3 |
+
size 876770627
|
data/problems.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b9f3009c56da9877d6bab359fa3d85b2587c56a05bee22980bbc6c875d798745
|
| 3 |
+
size 74983733
|
manifest.json
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"release": "litgraph-20261112",
|
| 3 |
+
"schema_version": 1,
|
| 4 |
+
"files": {
|
| 5 |
+
"CHANGELOG.md": {
|
| 6 |
+
"bytes": 1024,
|
| 7 |
+
"sha256": "076a8d3b368e80173e57088552781cdbba73b80c94d8bc6f8d16d562d783176f"
|
| 8 |
+
},
|
| 9 |
+
"README.md": {
|
| 10 |
+
"bytes": 5707,
|
| 11 |
+
"sha256": "f33e3bea13bba1d372ce1c35bff014e4859b0c0341bcf433512b89cc7d79189b"
|
| 12 |
+
},
|
| 13 |
+
"api/library_api.py": {
|
| 14 |
+
"bytes": 27079,
|
| 15 |
+
"sha256": "17b3d21d76799e06ede2bdcb6c89fec5367eb456f0f60234ab13e6ef6dc0e5fe"
|
| 16 |
+
},
|
| 17 |
+
"api/library_api_agent_prompt.md": {
|
| 18 |
+
"bytes": 8842,
|
| 19 |
+
"sha256": "bcd934753c00d22a3d1267f01400595d0eb16fbe882426fd1e0ad2292542b772"
|
| 20 |
+
},
|
| 21 |
+
"api/library_api_docs.py": {
|
| 22 |
+
"bytes": 13152,
|
| 23 |
+
"sha256": "8f05bf8abd6829f476dc57da95d207f843269b81ad410162cbba4b6833eb0581"
|
| 24 |
+
},
|
| 25 |
+
"api/library_api_index.py": {
|
| 26 |
+
"bytes": 7445,
|
| 27 |
+
"sha256": "05363d0c31d73df8919c8d08fff69571bb29701fc701ee35fa944facfb32b4ab"
|
| 28 |
+
},
|
| 29 |
+
"api/library_query.py": {
|
| 30 |
+
"bytes": 6025,
|
| 31 |
+
"sha256": "a4a389d9e9589ab4cda2adb6da1aad53a3ecf3b7970dbe7047f075c534a8a617"
|
| 32 |
+
},
|
| 33 |
+
"data/domain_papers.parquet": {
|
| 34 |
+
"bytes": 1103057,
|
| 35 |
+
"sha256": "70b7b44dad6396cebb6cb341145012a2ccda6bb0090a76d15a760b520cd1c3e5"
|
| 36 |
+
},
|
| 37 |
+
"data/domains.parquet": {
|
| 38 |
+
"bytes": 903588,
|
| 39 |
+
"sha256": "d05559df3c7a6e814bf70a36500283928bc87a42edf7bf51a676286cd28b29e6"
|
| 40 |
+
},
|
| 41 |
+
"data/insights.parquet": {
|
| 42 |
+
"bytes": 103279130,
|
| 43 |
+
"sha256": "82d22c7b8919c9122f52d403bcc9bb856fc8ef9b6c800cb54f1d9cbddd42f2fe"
|
| 44 |
+
},
|
| 45 |
+
"data/papers.parquet": {
|
| 46 |
+
"bytes": 876770627,
|
| 47 |
+
"sha256": "62101a0f4a20e091d59f8ed4233064bd6a3f169a075df9d70e2f1f8fda27fae9"
|
| 48 |
+
},
|
| 49 |
+
"data/problems.parquet": {
|
| 50 |
+
"bytes": 74983733,
|
| 51 |
+
"sha256": "b9f3009c56da9877d6bab359fa3d85b2587c56a05bee22980bbc6c875d798745"
|
| 52 |
+
},
|
| 53 |
+
"serve.py": {
|
| 54 |
+
"bytes": 2436,
|
| 55 |
+
"sha256": "c21a0ab860559e0114c65e060b7ae51a78ddb5710e1b4fe49d86e5f2c30224f1"
|
| 56 |
+
},
|
| 57 |
+
"snapshot/api_index.db": {
|
| 58 |
+
"bytes": 747573248,
|
| 59 |
+
"sha256": "222b0300bed5ff27ede83067301d6958d5ba5d4a397a2eda24814c6dbc119b8a"
|
| 60 |
+
},
|
| 61 |
+
"snapshot/domains.json": {
|
| 62 |
+
"bytes": 2131813,
|
| 63 |
+
"sha256": "dc5e74fd69f1a36c5b3b618274639b2450a5256d2f254d79603e3cc037344d95"
|
| 64 |
+
},
|
| 65 |
+
"snapshot/library.db": {
|
| 66 |
+
"bytes": 2443898880,
|
| 67 |
+
"sha256": "62a604878de989d0189db479e64bef0edfb243e94a67f39a2885620069d133fd"
|
| 68 |
+
},
|
| 69 |
+
"statistics.json": {
|
| 70 |
+
"bytes": 1330,
|
| 71 |
+
"sha256": "ac9f0dc06be6ef7e78e62ed99148cb9489fcbedb0a8a70b55d272abe320d2207"
|
| 72 |
+
}
|
| 73 |
+
},
|
| 74 |
+
"payload_bytes": 4250717116
|
| 75 |
+
}
|
serve.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Verify and run a downloaded LitGraph snapshot; Python 3.10+ standard library."""
|
| 2 |
+
import argparse
|
| 3 |
+
import hashlib
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import sqlite3
|
| 8 |
+
import sys
|
| 9 |
+
import tempfile
|
| 10 |
+
|
| 11 |
+
ROOT = Path(__file__).resolve().parent
|
| 12 |
+
|
| 13 |
+
def digest(path):
|
| 14 |
+
h = hashlib.sha256()
|
| 15 |
+
with path.open('rb') as stream:
|
| 16 |
+
for block in iter(lambda: stream.read(8 * 1024 * 1024), b''):
|
| 17 |
+
h.update(block)
|
| 18 |
+
return h.hexdigest()
|
| 19 |
+
|
| 20 |
+
def prepare(work_dir):
|
| 21 |
+
manifest = json.loads((ROOT / 'manifest.json').read_text())
|
| 22 |
+
for name in ('snapshot/library.db', 'snapshot/api_index.db'):
|
| 23 |
+
if digest(ROOT / name) != manifest['files'][name]['sha256']:
|
| 24 |
+
raise ValueError('Checksum mismatch: ' + name)
|
| 25 |
+
sys.path.insert(0, str(ROOT / 'api'))
|
| 26 |
+
from library_api_index import fingerprint
|
| 27 |
+
db = ROOT / 'snapshot/library.db'
|
| 28 |
+
canonical = ROOT / 'snapshot/api_index.db'
|
| 29 |
+
work_dir.mkdir(parents=True, exist_ok=True)
|
| 30 |
+
# A download changes timestamps. Rebind only a verified local index copy.
|
| 31 |
+
fd, temp_name = tempfile.mkstemp(prefix='index-', suffix='.db', dir=work_dir)
|
| 32 |
+
os.close(fd)
|
| 33 |
+
temporary = Path(temp_name)
|
| 34 |
+
try:
|
| 35 |
+
with sqlite3.connect(canonical.as_uri() + '?mode=ro', uri=True) as source:
|
| 36 |
+
with sqlite3.connect(temporary) as dest:
|
| 37 |
+
source.backup(dest)
|
| 38 |
+
dest.execute("UPDATE metadata SET value=? WHERE key='source'", (json.dumps(fingerprint(db)),))
|
| 39 |
+
dest.commit()
|
| 40 |
+
target = work_dir / 'api_index.db'
|
| 41 |
+
os.replace(temporary, target)
|
| 42 |
+
finally:
|
| 43 |
+
temporary.unlink(missing_ok=True)
|
| 44 |
+
return db, target
|
| 45 |
+
|
| 46 |
+
def main():
|
| 47 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 48 |
+
parser.add_argument('--host', default='127.0.0.1')
|
| 49 |
+
parser.add_argument('--port', type=int, default=8895)
|
| 50 |
+
parser.add_argument('--work-dir', type=Path, default=ROOT / '.runtime')
|
| 51 |
+
parser.add_argument('--verify-only', action='store_true')
|
| 52 |
+
args = parser.parse_args()
|
| 53 |
+
db, index = prepare(args.work_dir.resolve())
|
| 54 |
+
if args.verify_only:
|
| 55 |
+
from library_api import Library
|
| 56 |
+
print(json.dumps(Library(db, index).stats(), indent=2))
|
| 57 |
+
return
|
| 58 |
+
from library_api import main as serve
|
| 59 |
+
sys.argv = ['library_api.py', 'serve', '--db', str(db), '--index', str(index),
|
| 60 |
+
'--public', '--host', args.host, '--port', str(args.port)]
|
| 61 |
+
serve()
|
| 62 |
+
|
| 63 |
+
if __name__ == '__main__':
|
| 64 |
+
main()
|
snapshot/api_index.db
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:222b0300bed5ff27ede83067301d6958d5ba5d4a397a2eda24814c6dbc119b8a
|
| 3 |
+
size 747573248
|
snapshot/domains.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
snapshot/library.db
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:62a604878de989d0189db479e64bef0edfb243e94a67f39a2885620069d133fd
|
| 3 |
+
size 2443898880
|
statistics.json
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"domains": 856,
|
| 3 |
+
"unique_papers": 256227,
|
| 4 |
+
"domain_paper_assignments": 256361,
|
| 5 |
+
"entries": 105159,
|
| 6 |
+
"counts": {
|
| 7 |
+
"insight_domain": 13924,
|
| 8 |
+
"insight_cases": 39377,
|
| 9 |
+
"problem_domain": 14264,
|
| 10 |
+
"problem_cases": 37594,
|
| 11 |
+
"source_cards": 256129
|
| 12 |
+
},
|
| 13 |
+
"metadata_only_papers": 98,
|
| 14 |
+
"source_card_basis": {
|
| 15 |
+
"abstract": 116660,
|
| 16 |
+
"unspecified": 110330,
|
| 17 |
+
"fulltext": 29139
|
| 18 |
+
},
|
| 19 |
+
"paper_card_fields": {
|
| 20 |
+
"thesis": 256129,
|
| 21 |
+
"claim_type": 256129,
|
| 22 |
+
"problem": 256129,
|
| 23 |
+
"insight": 256129,
|
| 24 |
+
"observations": 256129,
|
| 25 |
+
"assumptions": 256129,
|
| 26 |
+
"evaluation": 256129,
|
| 27 |
+
"boundaries": 256129,
|
| 28 |
+
"evidence": 256129,
|
| 29 |
+
"technique": 256129,
|
| 30 |
+
"relations": 256129,
|
| 31 |
+
"paper_id": 256129,
|
| 32 |
+
"year": 256129,
|
| 33 |
+
"venue": 256129,
|
| 34 |
+
"title": 256129,
|
| 35 |
+
"arxiv": 256129,
|
| 36 |
+
"categories": 256129,
|
| 37 |
+
"source": 145799,
|
| 38 |
+
"model": 75535,
|
| 39 |
+
"scope": 13
|
| 40 |
+
},
|
| 41 |
+
"credential_pattern_hits": 0,
|
| 42 |
+
"private_host_path_hits": 0,
|
| 43 |
+
"entries_source_sha256": "3a1052512f7f22c4bd6680b034aec6a70943b4cd5b95686f9f5684866f06c8df",
|
| 44 |
+
"cards_source_sha256": "7458ec4ed0c21d1427bbb2ce13acd005d2d449bc412d25654e65bfbd3a4b091d",
|
| 45 |
+
"catalog_sha256": "dc5e74fd69f1a36c5b3b618274639b2450a5256d2f254d79603e3cc037344d95",
|
| 46 |
+
"metadata_input_sha256": "e6d1e72cbd2065be3f395da3bbfbf38edcffd080d7aea3a6b7ee81cbfff4b3d3"
|
| 47 |
+
}
|