Skip to content
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ internal versions are summarized under 0.3.33.
## [Unreleased]

### Added
- Restore released FAISS files on CPU with verified passage IDs, or fetch matching PMC full text and PubMed abstracts on demand. (#65)
- `litkit export-vectors` writes FAISS indexes, text hashes, source checksums, model revisions and per-paper attribution. Use `--license` to select licenses. (#65)
- Paper and passage results report publication type and retraction status. Search with repeatable `--type` and `--exclude-type` filters. (#58)
- `litkit build-fts` indexes passage text for exact search. The optional index stays current through updates, rebuilds and shard merges. (#56)
Expand Down
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -255,3 +255,24 @@ name. For example, `{"sources":{"old.tar":{"chunk_overlap":100}}}` fills that
archive's missing overlap setting. Supply all unrecorded fields for legacy
archives. Recorded settings must agree with the values supplied for that archive.
Use `--source-root DIR` when the legacy archives have moved.

Restore the normal searchable workspace on CPU with
`litkit rebuild-from-vectors RELEASE --sources ARCHIVE_DIR --workspace NEW_WORKSPACE`.
Use the relative archive names in the manifest. The JSON report lists changed,
new and missing sources, papers and chunk IDs. Matching text retains its
original vector. When all rows match, the FAISS files are copied unchanged
and no embedding model is loaded. Re-embedding changed or new inputs uses the
recorded model snapshots in the Hugging Face cache (`--hf-home`).

To retrieve passages before downloading the bulk archives, run
`litkit search-vectors RELEASE "query" --mode semantic --limit 10 --cache DIR`.
LitKit searches the chunk index and checks each requested passage against its
recorded text hash. It can recover an abstract from PubMed and body passages
from Europe PMC for the same paper. Each hit includes the license and
publication status of its source XML. Its `source_identifier` gives the PMCID
or PMID used for the request, or `null` for an older cache with unknown origin.
The JSON output includes identifiers and titles for unavailable or changed passages.
Hybrid mode reranks the fetched candidates using lexical and semantic ranks.
Queries require the recorded chunk embedding model. Subsequent queries reuse
the cached XML. Pass the same `--cache DIR` to a rebuild to recover verified
articles that are missing from the bulk sources.
4 changes: 3 additions & 1 deletion src/litkit/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1845,7 +1845,7 @@ def main():
sys.stderr.write("[env] Python >= 3.10 required.\n")
sys.exit(2)

if sys.argv[1:2] == ["export-vectors"]:
if sys.argv[1:2] and sys.argv[1] in {"export-vectors", "rebuild-from-vectors", "search-vectors"}:
from litkit.portable.cli import main as portable_main
portable_main(sys.argv[1:])
return
Expand Down Expand Up @@ -1908,6 +1908,8 @@ def main():
description="An air-gapped HPC two-stage RAG pipeline for the PMC-OA corpus",
epilog=(
" litkit export-vectors DIR Export vectors and a text-free passage mapping\n"
" litkit rebuild-from-vectors Restore a workspace from a vector release\n"
" litkit search-vectors Fetch verified passages from a vector release\n"
" litkit build-fts [--workspace DIR] Index passage text for exact search\n"
"Progressive retrieval subcommands (all support --json, --limit, --max-chars):\n"
" litkit search-papers [query] Stage-1 / metadata search with filters\n"
Expand Down
30 changes: 25 additions & 5 deletions src/litkit/embeddings/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

from __future__ import annotations

import json
from pathlib import Path
from typing import Any

from .base import Embedder # protocol for type hints
Expand All @@ -10,7 +12,24 @@
from .specter2 import SPECTER2_ID, PaperEmbedderSpecter2


def make_paper_embedder() -> tuple[Embedder, dict[str, Any]]:
def _workspace_model(db_path, kind):
"""A restored index must continue to use its release's embedding space."""
from litkit.config.paths import WorkspacePaths
from litkit.db.handoff import readable_database
from litkit.db.schema import get_workspace_meta

path = db_path if db_path is not None else WorkspacePaths.from_env_or_default().db_path
if not path.is_file():
return {}
with readable_database(path) as db:
record = get_workspace_meta(db, "vector_release_models")
if not record:
return {}
model = json.loads(record).get(kind)
return {"model_id": model["name"], "revision": model["revision"]} if model else {}


def make_paper_embedder(*, db_path: Path | None = None) -> tuple[Embedder, dict[str, Any]]:
"""
Instantiate the paper-level embedder (SPECTER2).

Expand All @@ -20,12 +39,12 @@ def make_paper_embedder() -> tuple[Embedder, dict[str, Any]]:
embedder : object implementing Embedder.encode(list[str]) -> np.ndarray
cfg : dict with metadata (model id, dim, device info if available)
"""
e = PaperEmbedderSpecter2() # Paper embedder handles its own device selection
e = PaperEmbedderSpecter2(**_workspace_model(db_path, "papers"))
dim = getattr(e, "dim", 768)
cfg = {
"type": "paper",
"impl": "PaperEmbedderSpecter2",
"model_id": SPECTER2_ID, # informational only
"model_id": getattr(e, "model_id", SPECTER2_ID),
"dim": int(dim),
"device": getattr(e, "device", detect_device()),
}
Expand All @@ -37,6 +56,7 @@ def make_chunk_embedder(
*,
workers: int = 1,
force_devices: bool = False,
db_path: Path | None = None,
) -> tuple[Embedder, dict[str, Any]]:
"""
Instantiate the chunk-level embedder (SBERT all-mpnet-base-v2).
Expand All @@ -59,12 +79,12 @@ def make_chunk_embedder(

spec = ",".join(devices) if isinstance(devices, list) else (devices or "auto")
dev_list = resolve_embed_devices(spec, force=force_devices)
e = ChunkEmbedderSBERT(devices=dev_list, workers=workers)
e = ChunkEmbedderSBERT(devices=dev_list, workers=workers, **_workspace_model(db_path, "chunks"))
dim = getattr(e, "dim", 768)
cfg = {
"type": "chunk",
"impl": "ChunkEmbedderSBERT",
"model_id": SBERT_ID,
"model_id": getattr(e, "model_id", SBERT_ID),
"dim": int(dim),
"devices": list(dev_list),
"workers": int(workers),
Expand Down
9 changes: 8 additions & 1 deletion src/litkit/embeddings/hf_local.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def repo_root(repo_id: str, hf_home: str | Path | None = None) -> Path:


def local_snapshot_dir(
repo_id: str, branch: str = "main", hf_home: str | Path | None = None
repo_id: str, branch: str = "main", hf_home: str | Path | None = None, *, revision: str | None = None
) -> Path:
"""Resolve a usable local snapshot directory for `repo_id`.

Expand All @@ -62,6 +62,13 @@ def local_snapshot_dir(
"""
root = repo_root(repo_id, hf_home=hf_home)
snaps = root / "snapshots"
if revision is not None:
if revision in {"", ".", ".."} or Path(revision).name != revision:
raise ValueError(f"Invalid snapshot revision {revision!r}")
snapshot = snaps / revision
if not snapshot.is_dir():
raise FileNotFoundError(f"Missing pinned snapshot {repo_id}@{revision} under {snaps}")
return snapshot
ref = root / "refs" / branch
if ref.exists():
commit = ref.read_text().strip()
Expand Down
6 changes: 3 additions & 3 deletions src/litkit/embeddings/sbert_mpnet.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ class ChunkEmbedderSBERT:
- If multiple CUDA devices requested, a background EmbeddingPool is used.
"""

def __init__(self, devices: list[str] | None = None, workers: int = 1):
def __init__(self, devices: list[str] | None = None, workers: int = 1, *, model_id: str = SBERT_ID, revision: str | None = None):
from sentence_transformers import SentenceTransformer # import lazily

self.devices = list(devices) if devices else [detect_device()]
Expand All @@ -50,8 +50,8 @@ def __init__(self, devices: list[str] | None = None, workers: int = 1):
if self.workers > 0 and len(self.devices) > self.workers:
self.devices = self.devices[: self.workers]

self.model_id = SBERT_ID
model_path = local_snapshot_dir(SBERT_ID) # must exist for offline runs
self.model_id = model_id
model_path = local_snapshot_dir(model_id, revision=revision) if revision else local_snapshot_dir(model_id)

self.revision = model_path.name

Expand Down
3 changes: 2 additions & 1 deletion src/litkit/embeddings/specter2.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,15 @@ def __init__(
self,
model_id: str = SPECTER2_ID,
device: str | None = None,
*, revision: str | None = None,
) -> None:
# torch is imported here, not at module level, so that importing litkit
# (retrieval, build, the CLI) doesn't load torch until a model is built.
import torch

self.model_id = model_id
self.device = device or detect_device()
local_path = local_snapshot_dir(self.model_id)
local_path = local_snapshot_dir(model_id, revision=revision) if revision else local_snapshot_dir(model_id)
self.revision = local_path.name
self.tok, self.model = load_auto_or_fallback(local_path, device=self.device)
self.model.eval()
Expand Down
7 changes: 3 additions & 4 deletions src/litkit/index/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,8 +170,8 @@ def faiss_load(path: Path) -> faiss.Index:
def faiss_load_cached(path: Path) -> faiss.Index:
"""Load a FAISS index with thread-local caching.

Caches indices by (path, mtime) to avoid repeated disk I/O during
search operations. Cache is invalidated when file is modified.
Cache by file identity, size and timestamps so an atomic replacement that
preserves modification time cannot reuse the previous index.

Args:
path: Path to the index file
Expand All @@ -186,8 +186,7 @@ def faiss_load_cached(path: Path) -> faiss.Index:
except FileNotFoundError:
return faiss_load(path)

mt_ns = getattr(st, "st_mtime_ns", int(st.st_mtime * 1_000_000_000))
key = (str(p.resolve()), mt_ns)
key = (str(p.resolve()), st.st_dev, st.st_ino, st.st_size, st.st_mtime_ns, st.st_ctime_ns)

cache = getattr(_TL_FAISS_CACHE, "faiss", None)
if cache is None:
Expand Down
174 changes: 174 additions & 0 deletions src/litkit/portable/articles.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
"""Read and verify article inputs for local rebuilds and on-demand passage search."""

from __future__ import annotations

import hashlib
import io
import os
import re
import tempfile
from pathlib import Path

from lxml import etree

from litkit.build.helpers import article_passages, paper_input
from litkit.concurrent.locking import FileLock
from litkit.ingest.ingest import _parse_tree
from litkit.ingest.publication_types import publication_fields, publication_source
from litkit.portable.release import digest


def passages(meta, settings):
return article_passages(
meta,
paper_input(meta),
settings["chunk_target_chars"],
settings["chunk_min_chars"],
settings["chunk_overlap"],
)


def parser_options(settings):
return {key: settings[key] for key in ("include_tables", "max_table_chars")}


def license_allowed(meta, manifest):
return not manifest["licenses"] or (meta.get("license") or "unknown") in manifest["licenses"]


def prepare_shared_editions(mapping):
# Earlier releases only recorded the final owner of each member name.
if not mapping.execute("SELECT 1 FROM sqlite_master WHERE name='shared_editions'").fetchone():
mapping.execute(
"""CREATE TEMP VIEW IF NOT EXISTS shared_editions AS
SELECT a.id AS paper_id,f.source,f.member FROM articles a JOIN files f
ON f.original=a.current_file WHERE a.id<>f.paper_id"""
)


def article_sources(mapping, paper_id):
rows = mapping.execute(
"""SELECT f.source,f.member FROM files f JOIN articles a ON a.id=f.paper_id
WHERE a.id=? AND (a.current_file IS NULL OR a.current_file=f.original) ORDER BY f.original""",
(paper_id,),
).fetchall()
return (
rows
or mapping.execute(
"SELECT source,member FROM shared_editions WHERE paper_id=?", (paper_id,)
).fetchall()
)


def settings_for_article(paper_id, locations, sources):
options = [sources[name] for name, _ in locations]
if not options or any(config != options[0] for config in options[1:]):
raise ValueError(f"Cannot determine unique build settings for paper {paper_id}")
return options[0]


def model_settings(manifest, kind):
key = "paper_model" if kind == "papers" else "chunk_model"
models = [s["settings"][key] for s in manifest["sources"]]
if not models or any(m != models[0] for m in models[1:]):
raise ValueError(f"Cannot search or extend {kind} with mixed or missing model revisions")
return models[0]


def load_model(kind, mode, model):
"""Instantiate only the exact local snapshot needed for a query or changed inputs."""
from litkit.embeddings.sbert_mpnet import ChunkEmbedderSBERT
from litkit.embeddings.specter2 import PaperEmbedderSpecter2

options = dict(model_id=model["name"], revision=model["revision"])
if kind == "papers" and mode == "specter2":
return PaperEmbedderSpecter2(device="cpu", **options)
return ChunkEmbedderSBERT(devices=["cpu"], **options)


def cache_path(root, manifest, pid):
return Path(root) / manifest["checksums"]["mapping.sqlite3"] / f"{pid}.xml"


def cache_sources(path, metadata):
"""Return each fetchable identifier and its XML cache, plus any older shared cache."""
identifiers = [metadata.get(key) for key in ("pmcid", "pmid")]
if metadata.get("article_type") is None and metadata.get("publication_types"):
identifiers.reverse()
identifiers = [i for i in identifiers if re.fullmatch(r"(?:PMC)?[0-9]+", i or "")]
if len(identifiers) < 2:
return [(identifiers[0] if identifiers else None, path)]
# Older two-identifier downloads did not record which endpoint supplied them.
return [(i, path.with_name(f"{path.stem}.{i}.xml")) for i in identifiers] + [(None, path)]


def parse_cached(raw, metadata, settings):
parser = etree.XMLParser(
resolve_entities=False, load_dtd=False, no_network=True, huge_tree=True
)
try:
tree = etree.parse(io.BytesIO(raw), parser)
except (ValueError, etree.XMLSyntaxError) as error:
raise ValueError("Incomplete or invalid article XML") from error
meta = _parse_tree(tree, "", **parser_options(settings))
if meta is None:
raise ValueError("Missing article record")
identifiers = [(metadata.get(k), meta.get(k)) for k in ("pmcid", "pmid")]
if not any(a and a == b for a, b in identifiers) or any(
a and b and a != b for a, b in identifiers
):
raise ValueError("Fetched article identifiers differ from the release")
return meta


def status_fields(meta, content_sha, original_member, released):
"""Carry a sidecar's status only when the exact publisher member can be verified."""
fingerprint = released.get("publication_source")
if (
original_member
and fingerprint
and publication_source(original_member, content_sha).hex() == fingerprint
):
return {k: released.get(k) for k in ("article_type", "publication_types", "retracted")}
raw_type, types, retracted = publication_fields(meta, None)
return dict(article_type=raw_type, publication_types=types, retracted=retracted)


def write_cache(path, raw):
path.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as handle:
temporary = Path(handle.name)
try:
temporary.write_bytes(raw)
os.replace(temporary, path)
finally:
temporary.unlink(missing_ok=True)


def write_cached_article(path, raw):
# Serialize both replacements. An interrupted write is detected by the
# checksum before the next reader accepts the XML.
with FileLock(path.parent / ".article-cache.lock"):
write_cache(path.with_suffix(".sha256"), hashlib.sha256(raw).hexdigest().encode("ascii"))
write_cache(path, raw)


def read_cached_article(path, mapping, pid, metadata, settings):
raw = path.read_bytes()
try:
expected = path.with_suffix(".sha256").read_bytes()
except FileNotFoundError:
expected = None
if expected is not None and hashlib.sha256(raw).hexdigest().encode("ascii") != expected:
raise ValueError("Cached article checksum mismatch")
meta = parse_cached(raw, metadata, settings)
if expected is None and not verified_article(mapping, pid, meta, settings):
raise ValueError("Unverified legacy cached article")
return raw, meta


def verified_article(mapping, pid, meta, settings):
expected = dict(mapping.execute("SELECT ord,digest FROM passages WHERE paper_id=?", (pid,)))
actual = {ordinal: digest(text) for ordinal, text, *_ in passages(meta, settings)}
paper_hash = mapping.execute("SELECT digest FROM articles WHERE id=?", (pid,)).fetchone()[0]
return paper_hash == digest(paper_input(meta)) and expected == actual
Loading
Loading