56 lines
1.9 KiB
Python
56 lines
1.9 KiB
Python
"""Chunk, embed and store a BEIR corpus."""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
|
|
|
|
from raglab.chunking import chunk_markdown # noqa: E402
|
|
from raglab.config import Settings # noqa: E402
|
|
from raglab.db import apply_schema, insert_chunks, reset # noqa: E402
|
|
from raglab.embed import embed_passages # noqa: E402
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--data", default="data/scifact")
|
|
parser.add_argument("--schema", default="sql/schema.sql")
|
|
parser.add_argument("--limit-docs", type=int, default=0)
|
|
parser.add_argument("--batch", type=int, default=256)
|
|
args = parser.parse_args()
|
|
|
|
settings = Settings.from_env()
|
|
apply_schema(settings, args.schema)
|
|
|
|
rows = [json.loads(line) for line in (Path(args.data) / "corpus.jsonl").read_text(encoding="utf-8").splitlines() if line]
|
|
if args.limit_docs:
|
|
rows = rows[: args.limit_docs]
|
|
|
|
chunks = []
|
|
for row in rows:
|
|
doc_id = row["_id"]
|
|
title = row.get("title") or ""
|
|
chunks.extend(chunk_markdown(doc_id, f"# {title}\n\n{row.get('text', '')}"))
|
|
|
|
print(f"docs={len(rows)} chunks={len(chunks)}")
|
|
reset(settings)
|
|
for start in range(0, len(chunks), args.batch):
|
|
batch = chunks[start : start + args.batch]
|
|
vectors = embed_passages(settings.embed_model, [c.text for c in batch])
|
|
insert_chunks(
|
|
settings,
|
|
[
|
|
{"id": c.id, "doc_id": c.doc_id, "title": c.title, "text": c.text, "meta": {**c.meta, "chunk": c.id}, "embedding": vec}
|
|
for c, vec in zip(batch, vectors, strict=True)
|
|
],
|
|
)
|
|
print(f"inserted {min(start + args.batch, len(chunks))}/{len(chunks)}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|