"""Build the downloadable Windows reference index and exact GPUless examples.""" import csv import hashlib import json import re import sqlite3 from pathlib import Path from runtime.reference import evidence_prompt, retrieve def sections(raw): text = raw.split("\n---\n", 1)[-1] text = re.sub(r"```.*?```", "", text, flags=re.S) text = re.sub(r"!\[[^\]]*\]\([^)]*\)", "", text) text = re.sub(r"\[([^\]]+)\]\([^)]*\)", r"\1", text) text = text.replace("**", "").replace("\xa0", " ") title = re.search(r"^# (.+)", text, re.M)[1].strip() pending = [] for block in re.split(r"\n\s*\n", text): block = " ".join(block.split()).strip() if not block or block.startswith(("#", "<", "[!")): continue # Windows docs have long list and table paragraphs. Keep words intact. words = block.split() while words: take = min(125 - len(pending), len(words)) pending += words[:take] words = words[take:] if len(pending) == 125: yield title, " ".join(pending) pending = [] if len(pending) >= 65: yield title, " ".join(pending) pending = [] if pending: yield title, " ".join(pending) def build(root): sources = json.loads((root / "sources.json").read_text()) path = root / "windows.sqlite" temp = path.with_suffix(".new") if temp.exists(): raise FileExistsError(temp) with sqlite3.connect(temp) as db: db.execute( "CREATE VIRTUAL TABLE passages USING fts5(title,body,url UNINDEXED,source UNINDEXED,tokenize='porter unicode61')" ) for doc in sources: db.executemany( "INSERT INTO passages VALUES(?,?,?,?)", ( (t, b, doc["url"], doc["id"]) for t, b in sections((root / doc["file"]).read_text()) ), ) db.commit() db.close() temp.replace(path) records = [] with (root / "data/questions.tsv").open() as stream: questions = list(csv.DictReader(stream, delimiter="\t")) train_sources = {r["source"] for r in questions if r["split"] == "train"} for row in questions: q = row["question"] for condition in ("closed", "rag"): hits = retrieve(path, q) if condition == "rag" else [] gold = row["source"] # Training retrieval uses training references only. The released index # covers the full reference collection, including held-out sources. if row["split"] == "train" and condition == "rag": hits = [h for h in hits if h["id"] in train_sources] target = row["answer"] if condition == "rag": match = next((h for h in hits if h["id"] == gold), None) if match: target += f" [{match['title']}]({match['url']})" elif row["split"] == "train": target = ( "The retrieved references do not establish that. I need a source on " + gold.replace("-", " ") + "." ) records.append( { "id": hashlib.sha256(q.encode()).hexdigest()[:16], "split": row["split"], "passage": gold, "condition": condition, "question": q, "answer": target, "prompt": evidence_prompt(q, hits) if condition == "rag" else "Answer the Windows question concisely.\nQuestion: " + q, "retrieved": [h["id"] for h in hits], } ) for name, rows in [ ("examples", records), ("train", [r for r in records if r["split"] == "train"]), ("eval", [r for r in records if r["split"] == "test"]), ]: (root / "data" / (name + ".jsonl")).write_text( "".join(json.dumps(r, ensure_ascii=False) + "\n" for r in rows) ) # Additional operator-written notes ship with the inference pack. They # are added after freezing examples and cannot change a training prompt. with sqlite3.connect(path) as db: for card in json.loads((root / "data/additional-references.json").read_text()): db.execute( "INSERT INTO passages VALUES(?,?,?,?)", (card["title"], card["body"], card["url"], card["id"]), ) db.close() print(len(sources), "sources;", len(records), "examples") if __name__ == "__main__": build(Path(__file__).resolve().parent)