File size: 4,195 Bytes
2ff8533
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Stage 2: download each needed upstream file ONE AT A TIME, pull out only the planned rows (low memory: row batches), convert with the
ORIGINAL build's functions (cyber/build_cyber_dataset.py) and append to gzip scratch files. Resumable (done-file list); deletes each
download right after use."""
import gzip, json, os, sys, time, collections
import pyarrow.parquet as pq
import pandas as pd
import huggingface_hub as hf
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from common import *
import build_cyber_dataset as orig        # original converters: messages_from_*, cve_answer, CVE_SYSTEM, to_native

plan = json.load(open(os.path.join(SCRATCH, "plan.json")))
done_path = os.path.join(SCRATCH, "extract_done.json")
done = set(json.load(open(done_path))) if os.path.exists(done_path) else set()
t0 = time.time()

def drop(path):
    for p in {path, os.path.realpath(path)}:
        try: os.remove(p)
        except OSError: pass

def get_out(outs, stream):
    # NOT outs.setdefault(stream, writer(stream)): that opens a NEW gzip handle for every row and corrupts the file
    if stream not in outs:
        outs[stream] = writer(stream)
    return outs[stream]

def writer(stream):
    return gzip.open(os.path.join(SCRATCH, "rows_" + stream.replace("/", "_").replace(":", "_") + ".jsonl.gz"), "at", encoding="utf-8", compresslevel=3)

# group candidates: (repo, file) -> {id: (stream, rank)}
work = collections.defaultdict(dict)
for stream, s in plan["streams"].items():
    repo = SRC_NAME["swehero"] if stream == "swehero" else SRC_NAME["openswe"] if stream.startswith("openswe") else SRC_NAME["cve"]
    for rank, rid, f in s["candidates"]:
        work[(repo, f)][rid] = (stream, rank)
print(f"{len(work)} upstream files to process, {sum(len(v) for v in work.values())} candidate rows", flush=True)

for n, ((repo, f), need) in enumerate(sorted(work.items()), 1):
    key = repo + "|" + f
    if key in done:
        continue
    kw = {"revision": "refs/convert/parquet"} if repo == SRC_NAME["cve"] else {}
    path = hf.hf_hub_download(repo, f, repo_type="dataset", **kw)
    got = 0
    outs = {}
    if repo == SRC_NAME["cve"]:
        df = pd.read_parquet(path).drop_duplicates("CVE-ID").set_index("CVE-ID", drop=False)
        for rid, (stream, rank) in sorted(need.items(), key=lambda x: x[1][1]):
            cid = rid[len("cve-"):]
            if cid not in df.index: continue
            r = df.loc[cid]
            ans = orig.cve_answer(r)
            if len(ans) < 20: continue
            msgs = [{"role": "system", "content": orig.CVE_SYSTEM}, {"role": "user", "content": f"What is {cid} and how severe is it?"}, {"role": "assistant", "content": ans}]
            get_out(outs, stream).write(json.dumps(orig.to_native({"rk": rank, "id": rid, "source": repo, "messages": msgs}), ensure_ascii=False) + "\n")
            got += 1
    else:
        sw = repo == SRC_NAME["swehero"]
        cols = ["trajectory_id", "trajectory"] if sw else ["trajectory_id", "messages", "resolved"]
        pf = pq.ParquetFile(path)
        for batch in pf.iter_batches(batch_size=50, columns=cols):
            d = batch.to_pydict()
            for i, tid in enumerate(d["trajectory_id"]):
                rid = ("swehero-" if sw else "openswe-") + str(tid)
                if rid not in need: continue
                if not sw and d["resolved"][i] != 1: continue
                msgs = (orig.messages_from_swehero_trajectory if sw else orig.messages_from_openswe)(list(d["trajectory" if sw else "messages"][i]))
                if len(msgs) < 2: continue
                stream, rank = need[rid]
                get_out(outs, stream).write(json.dumps(orig.to_native({"rk": rank, "id": rid, "source": repo, "messages": msgs}), ensure_ascii=False) + "\n")
                got += 1
    for o in outs.values(): o.close()
    drop(path)
    done.add(key); json.dump(sorted(done), open(done_path, "w"))
    print(f"[{n}/{len(work)}] {repo.split('/')[-1][:28]:28s} {f[-52:]:52s} kept {got}/{len(need)}  {time.time()-t0:.0f}s", flush=True)
print("EXTRACT_DONE", flush=True)