Skip to content
Merged
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
- Index individual PMID records in PubMed baseline XML gzip files and multi-record tar members. Abstract-only papers remain searchable alongside PMC OA full text. (#73)
- 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)
Expand Down
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -276,3 +276,19 @@ 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.

### Building a combined PubMed and PMC corpus

Put the NLM annual PubMed baseline files (`pubmed*.xml.gz`) and PMC OA JATS tar
archives in the directory passed to `--tar-dir`, or list them in a tar
manifest. LitKit streams each PubMed citation using its own PMID. Papers with
an abstract and no PMCID are indexed and searchable. If a PMC article has the
same PMID, the index retains the full text and its body passages whichever
source is processed first. Many PubMed citations have no abstract from NLM.

Use an unfiltered vector export to retain every indexed abstract. PubMed
records often have no machine-readable license, so an export restricted to
named Creative Commons licenses omits them. A receiver can restore from the
same files or fetch matching abstracts by PMID during on-demand search.
The baseline reader stops if it encounters a daily-update `DeleteCitation`
notice. Deletion synchronization is separate from a fresh annual-baseline build.
166 changes: 98 additions & 68 deletions src/litkit/build/ingest_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from contextlib import ExitStack, nullcontext
from pathlib import Path
from types import SimpleNamespace
from typing import TYPE_CHECKING, Iterator, Sequence
from typing import IO, TYPE_CHECKING, Callable, Iterator, Sequence

import faiss

Expand All @@ -34,6 +34,7 @@
parallel_iter_tar_articles,
parse_xml_fileobj,
)
from litkit.ingest.pubmed_bulk import record_name
from litkit.ingest.publication_types import publication_fields, publication_source
from litkit.ingest import is_uncompressed_tar
from litkit.index import (
Expand Down Expand Up @@ -104,6 +105,7 @@ def iter_tar_articles(
*,
include_tables: bool = False,
max_table_chars: int = DEFAULT_MAX_TABLE_CHARS,
legacy_member: Callable[[str, IO[bytes]], bool] | None = None,
) -> Iterator[tuple[TarMemberMeta, ArticleMeta]]:
"""Unified iterator over articles in a tar file.

Expand All @@ -117,7 +119,7 @@ def iter_tar_articles(
"""
from litkit.progress import is_quiet

use_parallel = parse_workers > 1 and is_uncompressed_tar(tar_path)
use_parallel = legacy_member is None and parse_workers > 1 and is_uncompressed_tar(tar_path)

if use_parallel:
if not is_quiet():
Expand All @@ -131,7 +133,7 @@ def iter_tar_articles(
yield member_meta, article_meta
else:
# Sequential path for compressed tars (or when parallel disabled)
for tarinfo, fobj in iter_tar_xml_streams(tar_path):
for tarinfo, fobj in iter_tar_xml_streams(tar_path, legacy_member=legacy_member):
try:
reader = _HashingReader(fobj)
article_meta = parse_xml_fileobj(
Expand All @@ -146,6 +148,7 @@ def iter_tar_articles(
size=int(getattr(tarinfo, "size", 0)),
mtime=float(getattr(tarinfo, "mtime", 0.0) or 0.0),
content_sha256=reader.digest(),
bulk_record=getattr(tarinfo,"bulk_record",False),
)
yield member_meta, article_meta
finally:
Expand Down Expand Up @@ -531,7 +534,7 @@ def flush_tar_batch(members):
# Set LITKIT_TAR_PRESCAN=0 to skip counting members
total_members = (
count_tar_xml_members(tpath)
if os.environ.get("LITKIT_TAR_PRESCAN", "1") == "1"
if not tpath.name.lower().endswith(".xml.gz") and os.environ.get("LITKIT_TAR_PRESCAN", "1") == "1"
else None
)

Expand Down Expand Up @@ -612,8 +615,24 @@ def _render(force: bool = False):
include_tables=include_tables,
max_table_chars=max_table_chars,
):
f = f"tar://{tpath}!/{m.name}"
f = f"tar://{tpath}!/{record_name(m,meta)}"
if getattr(m, "bulk_record", False):
# The quick tar-header count omits siblings in an XML member.
total_members = None
manifest_article = manifest_articles.get(m.name.removeprefix("./"))
st = SimpleNamespace(
st_size=int(getattr(m, "size", 0)),
content_sha256=m.content_sha256 if getattr(m,"bulk_record",False) else None,
st_mtime=float(getattr(m, "mtime", 0.0) or 0.0),
)

if skipped < start_persisted and st.content_sha256:
# Older checkpoints counted whole XML members. Validate each bulk PMID before
# skipping its position, including when a distribution was revised or reordered.
local = db_already_processed(cur, f, st)
remote = merged_has_file_hash and db_already_processed(merged, f, st, require_indexed=True)
if not (local or remote):
start_persisted = processed_count = persisted_count = skipped
if skipped < start_persisted:
if manifest_article is not None and meta is not None:
refresh_known_member(f, m, meta, manifest_article)
Expand All @@ -624,11 +643,6 @@ def _render(force: bool = False):
_render(force=True) # render resume point
continue

st = SimpleNamespace(
st_size=int(getattr(m, "size", 0)),
st_mtime=float(getattr(m, "mtime", 0.0) or 0.0),
)

# ═══════════════════════════════════════════════════════════════════
# FAST PATH - No savepoint overhead for already-processed or unparsable
# ═══════════════════════════════════════════════════════════════════
Expand All @@ -639,7 +653,7 @@ def _render(force: bool = False):
# Fast path 1: already processed (vast majority in --update mode)
if not rebuilding_tar:
known = db_already_processed(cur, f, st)
if not known and merged is not None and db_already_processed(merged, f, st, require_indexed=True):
if not known and merged is not None and (not st.content_sha256 or merged_has_file_hash) and db_already_processed(merged, f, st, require_indexed=True):
known = not cur.execute("SELECT 1 FROM files WHERE path=?", (f,)).fetchone()
if known:
if manifest_article is not None and meta is not None:
Expand Down Expand Up @@ -749,8 +763,13 @@ def _render(force: bool = False):

ta_ab = paper_input(meta)
old_ids = []
reuse_embedding = False
if existing_row:
keep_full_text = bool(existing_row and meta.get("text_source") == "pubmed" and
cur.execute("""SELECT 1 FROM papers p WHERE p.id=? AND
(p.text_source='jats-full-text' OR (p.text_source IS NULL AND EXISTS
(SELECT 1 FROM chunks c WHERE c.paper_id=p.id AND c.ord>=0
AND coalesce(c.section,'')!='Abstract')))""",(pid,)).fetchone())
reuse_embedding = keep_full_text
if existing_row and not keep_full_text:
if previous_text is None:
prior = cur.execute(
"SELECT text FROM chunks WHERE paper_id=? AND ord=-1 ORDER BY id DESC LIMIT 1",
Expand Down Expand Up @@ -787,63 +806,72 @@ def _render(force: bool = False):
record_citation_link(cur, pid)

db_register_file(cur, str(f), pid, st)
# Another shard may have installed a different version
# since this retained shard last embedded the paper.
if paper_embedder is not None and (not reuse_embedding or shard_revision):
paper_ids_buf.append(pid)
paper_texts_buf.append(ta_ab)
paper_doc_ids_buf.append(canon_doc_id)
if existing_row or shard_revision:
if not shard_revision and not supplied_link:
pmid, pmcid = available_citation_ids(canon_doc_id, pmid, pmcid, cur, merged)
cur.execute(
"UPDATE papers SET title=?, abstract=?, source_path=?, embedding_text=?, "
"doi=COALESCE(NULLIF(?, ''), doi), "
"year=COALESCE(?, year), "
"authors=COALESCE(NULLIF(?, ''), authors), "
"journal=COALESCE(NULLIF(?, ''), journal), "
"pmid=COALESCE(NULLIF(pmid,''),?), pmcid=COALESCE(NULLIF(pmcid,''),?) WHERE id=?",
(
meta["title"],
meta["abstract"],
meta.get("source_path"),
ta_ab,
meta.get("doi"),
meta.get("year"),
meta.get("authors"),
meta.get("journal"),
pmid,
pmcid,
pid,
),
)
else:
cur.execute("UPDATE papers SET embedding_text=? WHERE id=?", (ta_ab, pid))

if provenance:
cur.execute("INSERT OR IGNORE INTO build_sources VALUES (?,?,?,?)", provenance)
cur.execute("UPDATE papers SET license=?,license_url=?,build_member=? WHERE id=?",
(meta.get("license"), meta.get("license_url"), f, pid))
bibliography = meta.get("references")
cur.execute("UPDATE papers SET references_json=?, publication_source=?, article_type=?, "
"publication_types=?, retracted=? WHERE id=?", (
json.dumps(bibliography, ensure_ascii=False) if bibliography is not None else None,
publication_source(f, m.content_sha256), *publication_fields(meta, manifest_article), pid,
))
if has_refresh_table:
cur.execute("DELETE FROM publication_refreshes WHERE path=?", (f,))
for ord_i, text_i, page, section, refs in article_passages(
meta, ta_ab, chunk_target_chars, chunk_min_chars, chunk_overlap
):
cur.execute(
"INSERT INTO chunks(paper_id, ord, text, page, section, cited_refs) VALUES (?,?,?,?,?,?)",
(pid, ord_i, text_i, page, section, json.dumps(refs) if refs else None),
)
cid = cur.lastrowid
chunk_ids_buf.append(cid)
chunk_texts_buf.append(text_i)
chunk_paper_doc_ids_buf.append(canon_doc_id)
chunk_ords_buf.append(ord_i)
if keep_full_text:
# PubMed-only records supplement the existing full text. Keep its
# passages, source-bound license/status, and existing FAISS labels.
cur.execute("""UPDATE papers SET pmid=coalesce(nullif(pmid,''),?),
pmcid=coalesce(nullif(pmcid,''),?), doi=coalesce(nullif(doi,''),?),
authors=coalesce(nullif(authors,''),?), journal=coalesce(nullif(journal,''),?),
year=coalesce(year,?) WHERE id=?""",
(pmid,pmcid,meta.get("doi"),meta.get("authors"),meta.get("journal"),meta.get("year"),pid))
else:
# Another shard may have installed a different version
# since this retained shard last embedded the paper.
if paper_embedder is not None and (not reuse_embedding or shard_revision):
paper_ids_buf.append(pid)
paper_texts_buf.append(ta_ab)
paper_doc_ids_buf.append(canon_doc_id)
if existing_row or shard_revision:
if not shard_revision and not supplied_link:
pmid, pmcid = available_citation_ids(canon_doc_id, pmid, pmcid, cur, merged)
cur.execute(
"UPDATE papers SET title=?, abstract=?, source_path=?, embedding_text=?, "
"doi=COALESCE(NULLIF(?, ''), doi), "
"year=COALESCE(?, year), "
"authors=COALESCE(NULLIF(?, ''), authors), "
"journal=COALESCE(NULLIF(?, ''), journal), "
"pmid=COALESCE(NULLIF(pmid,''),?), pmcid=COALESCE(NULLIF(pmcid,''),?) WHERE id=?",
(
meta["title"],
meta["abstract"],
meta.get("source_path"),
ta_ab,
meta.get("doi"),
meta.get("year"),
meta.get("authors"),
meta.get("journal"),
pmid,
pmcid,
pid,
),
)
else:
cur.execute("UPDATE papers SET embedding_text=? WHERE id=?", (ta_ab, pid))

cur.execute("UPDATE papers SET license=?,license_url=?,build_member=?,text_source=? WHERE id=?",
(meta.get("license"), meta.get("license_url"), f, meta.get("text_source"), pid))
bibliography = meta.get("references")
cur.execute("UPDATE papers SET references_json=?, publication_source=?, article_type=?, "
"publication_types=?, retracted=? WHERE id=?", (
json.dumps(bibliography, ensure_ascii=False) if bibliography is not None else None,
publication_source(f, m.content_sha256), *publication_fields(meta, manifest_article), pid,
))
if has_refresh_table:
cur.execute("DELETE FROM publication_refreshes WHERE path=?", (f,))
for ord_i, text_i, page, section, refs in article_passages(
meta, ta_ab, chunk_target_chars, chunk_min_chars, chunk_overlap
):
cur.execute(
"INSERT INTO chunks(paper_id, ord, text, page, section, cited_refs) VALUES (?,?,?,?,?,?)",
(pid, ord_i, text_i, page, section, json.dumps(refs) if refs else None),
)
cid = cur.lastrowid
chunk_ids_buf.append(cid)
chunk_texts_buf.append(text_i)
chunk_paper_doc_ids_buf.append(canon_doc_id)
chunk_ords_buf.append(ord_i)

# ---------- END INGEST BODY ----------

Expand Down Expand Up @@ -924,6 +952,7 @@ def _render(force: bool = False):
)
with owner_lock, ExitStack() as readers:
merged = None
merged_has_file_hash = False
merged_has_types = False
merged_sequence = 0
has_refresh_table = bool(conn.execute(
Expand Down Expand Up @@ -954,6 +983,7 @@ def _render(force: bool = False):
has_files = main_db.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='files'").fetchone()
if has_files and main_db.execute("SELECT 1 FROM files LIMIT 1").fetchone():
merged = main_db.cursor()
merged_has_file_hash = "content_sha256" in table_columns(main_db, "files")
merged_has_types = "publication_source" in table_columns(main_db, "papers")
merged_has_links = bool(merged.execute(
"SELECT 1 FROM sqlite_master WHERE name='paper_citation_links'"
Expand Down
Loading
Loading