cybermodels-web-defense / build_data.py
p4x-ng's picture
Stage Cybermodels v0.1 web-defense
e165512 verified
Raw History Blame Contribute Delete
3.31 kB
"""Rebuild one specialist's exact examples and offline FTS index from its source file."""
import hashlib
import json
import sqlite3
import tempfile
import tomllib
from contextlib import closing
from pathlib import Path
from grounding import prompt
from runtime.reference import retrieve
def index(path, cards):
with closing(sqlite3.connect(path)) as db, db:
db.execute(
"CREATE VIRTUAL TABLE passages USING fts5(title,body,url UNINDEXED,source UNINDEXED,tokenize='porter unicode61')"
)
db.executemany(
"INSERT INTO passages VALUES(?,?,?,?)",
((c["title"], c["notes"], c["url"], c["id"]) for c in cards),
)
def build(root):
data = root / "data"
config = tomllib.loads((data / "specialist.toml").read_text())
cards = config["source"]
for card in cards:
card["url"] = config["source_root"] + card["path"]
with tempfile.TemporaryDirectory(dir=root) as temp:
temp = Path(temp)
index(temp / "references.sqlite", cards)
index(
temp / "training.sqlite",
[c for c in cards if c.get("split", "train") == "train"],
)
records = []
for card in cards:
split = card.get("split", "train")
db = temp / ("training.sqlite" if split == "train" else "references.sqlite")
for question, answer in card["qa"]:
key = hashlib.sha256(question.encode()).hexdigest()[:16]
for condition in ("closed", "rag"):
hits = retrieve(db, question) if condition == "rag" else []
target = answer
if condition == "rag":
if any(h["id"] == card["id"] for h in hits):
target += f" [{card['title']}]({card['url']})"
else:
target = (
"The retrieved references do not establish that. I need a source on "
+ card["title"]
+ "."
)
records.append(
dict(
id=key,
passage=card["id"],
condition=condition,
split=split,
question=question,
answer=target,
retrieved=[h["id"] for h in hits],
prompt=prompt(config, question, hits)
if condition == "rag"
else f"Answer the {config['topic']} question concisely.\nQuestion: {question}",
)
)
for name, subset in (
("examples", records),
("train", [r for r in records if r["split"] == "train"]),
("eval", [r for r in records if r["split"] == "test"]),
):
(data / (name + ".jsonl")).write_text(
"".join(json.dumps(r, ensure_ascii=False) + "\n" for r in subset)
)
(temp / "references.sqlite").replace(root / "references.sqlite")
return records
if __name__ == "__main__":
build(Path(__file__).resolve().parent)