File size: 4,755 Bytes
3d81e63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
"""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)