File size: 4,359 Bytes
0b1f142 | 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 | """Reproduce the three nested Skill-Venus corpus subsets from corpus-full."""
import argparse
import hashlib
import json
import re
from collections import Counter
from contextlib import ExitStack
from pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parent
SIZES = {"corpus-50k": 50_000, "corpus-100k": 100_000, "corpus-500k": 500_000}
ID_AT_START = re.compile(rb'^\s*\{\s*"skill_id"\s*:\s*"([^"\\]+)"')
def skill_id(line):
match = ID_AT_START.match(line)
if match:
return match[1].decode("utf-8")
return json.loads(line)["skill_id"]
def select(full, required_path):
required = set(required_path.read_text(encoding="utf-8").splitlines())
with full.open("rb", buffering=1024 * 1024) as source:
ids = set()
for line in source:
current = skill_id(line)
if current in ids:
raise ValueError(f"Duplicate skill ID in {full}: {current}")
ids.add(current)
if not required <= ids:
raise ValueError(f"Missing required skill IDs: {sorted(required - ids)[:5]}")
if len(ids) < max(SIZES.values()) or len(required) > min(SIZES.values()):
raise ValueError("Corpus and required IDs cannot produce all three subset sizes.")
candidates = sorted(ids - required)
rng = np.random.default_rng(42)
if len(ids) == 964_775 and len(required) == 2_727:
removed_position = 5_710
order = rng.permutation(len(candidates) + 1)
order = order[order != removed_position]
order -= order > removed_position
else:
order = rng.permutation(len(candidates))
first_size = dict.fromkeys(required, 0)
start = 0
for i, count in enumerate(SIZES.values()):
end = count - len(required)
first_size.update((candidates[index], i) for index in order[start:end])
start = end
return first_size
def reproduce(full, first_size, output):
names = tuple(SIZES)
digests = {name: hashlib.sha256() for name in names}
counts = Counter()
with ExitStack() as stack:
if output is not None:
output.mkdir(parents=True, exist_ok=False)
files = {}
for name in names:
directory = output / name
directory.mkdir()
files[name] = stack.enter_context((directory / "skills.jsonl").open("xb"))
source = stack.enter_context(full.open("rb", buffering=1024 * 1024))
for line in source:
start = first_size.get(skill_id(line))
if start is None:
continue
for name in names[start:]:
counts[name] += 1
digests[name].update(line)
if output is not None:
files[name].write(line)
if counts != SIZES:
raise ValueError(f"Unexpected record counts: {dict(counts)}")
return {name: digests[name].hexdigest() for name in names}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--full", type=Path, default=HERE / "corpus-full/skills.jsonl")
parser.add_argument("--required-ids", type=Path, default=HERE / "required-skill-ids.txt")
mode = parser.add_mutually_exclusive_group(required=True)
mode.add_argument("--verify", action="store_true", help="Compare with the published subset manifests.")
mode.add_argument("--output", type=Path, help="Write the three subsets to a new directory.")
args = parser.parse_args()
if args.output is not None and args.output.exists():
parser.error("--output must be a new directory")
expected = {}
if args.verify:
for name in SIZES:
path = HERE / name / "manifest.json"
manifest = json.loads(path.read_text(encoding="utf-8"))
if manifest["documents"] != SIZES[name]:
raise ValueError(f"Unexpected record count in {path}")
expected[name] = manifest["skills_jsonl_sha256"]
selected = select(args.full, args.required_ids)
hashes = reproduce(args.full, selected, args.output)
for name, sha256 in hashes.items():
if args.verify and sha256 != expected[name]:
raise ValueError(f"{name} SHA-256 mismatch: {sha256}")
print(f"{name}: {SIZES[name]} records, SHA-256 {sha256}", flush=True)
if __name__ == "__main__":
main()
|