53 lines
2.1 KiB
Python
53 lines
2.1 KiB
Python
#!/usr/bin/env python3
|
|
"""Hold out a fixed share of technical documents from training, by path hash.
|
|
|
|
A document is held out when the first byte of sha256(source path) is below a threshold,
|
|
so the split is reproducible and does not depend on file order. Held-out documents go to
|
|
eval/technical_heldout.jsonl and are removed from the training corpus files written here.
|
|
"""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
|
|
def held_out(source, share):
|
|
digest = hashlib.sha256(source.encode("utf-8")).digest()
|
|
return digest[0] < int(share * 256)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--inputs", nargs="+", required=True, type=Path)
|
|
parser.add_argument("--share", type=float, default=0.1)
|
|
parser.add_argument("--train-dir", type=Path, default=Path("corpora"))
|
|
parser.add_argument("--eval-file", type=Path, default=Path("eval/technical_heldout.jsonl"))
|
|
args = parser.parse_args()
|
|
if args.eval_file.exists():
|
|
parser.error(f"refusing to overwrite: {args.eval_file}")
|
|
args.eval_file.parent.mkdir(parents=True, exist_ok=True)
|
|
summary = {}
|
|
with args.eval_file.open("x", encoding="utf-8") as heldout:
|
|
for path in args.inputs:
|
|
kept = removed = 0
|
|
out_path = args.train_dir / (path.stem + "-train.jsonl")
|
|
if out_path.exists():
|
|
parser.error(f"refusing to overwrite: {out_path}")
|
|
with path.open(encoding="utf-8") as source, out_path.open("x", encoding="utf-8") as train:
|
|
for line in source:
|
|
record = json.loads(line)
|
|
if held_out(record["source"], args.share):
|
|
heldout.write(json.dumps({**record, "from": path.name}, ensure_ascii=False) + "\n")
|
|
removed += 1
|
|
else:
|
|
train.write(line)
|
|
kept += 1
|
|
summary[path.name] = {"train_records": kept, "heldout_records": removed,
|
|
"train_file": str(out_path)}
|
|
print(json.dumps(summary, indent=2))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|