"""Build screen_set_v1.tsv by screen_rule_v1.txt. Reads only validation.tsv. usage: build_screen_set.py VALIDATION_TSV OUT_TSV """ import collections import hashlib import sys val_path, out_path = sys.argv[1], sys.argv[2] assert val_path.endswith("kohtd_split_v1/validation.tsv"), "only the validation split may be read" rows = [] with open(val_path, encoding="utf-8", newline="") as f: hdr = f.readline().rstrip("\n").split("\t") assert hdr == ["crop_file", "form_id", "label", "key_type"], hdr for line in f: parts = line.rstrip("\n").split("\t") assert len(parts) == 4, repr(line) rows.append(parts) by_form = collections.defaultdict(list) for crop_file, form_id, label, key_type in rows: h = hashlib.sha256(("J11-screen-v1:" + crop_file).encode("utf-8")).hexdigest() by_form[form_id].append((h, crop_file, label)) out = [] for form_id in sorted(by_form, key=lambda x: int(x)): items = sorted(by_form[form_id]) # ascending hex digest as text for h, crop_file, label in items[:15]: out.append((crop_file, form_id, label)) with open(out_path, "w", encoding="utf-8", newline="") as f: f.write("crop_file\tform_id\tlabel\n") for crop_file, form_id, label in out: f.write(f"{crop_file}\t{form_id}\t{label}\n") print("forms", len(by_form), "crops in list", len(out)) print("forms with fewer than 15 crops", sum(1 for v in by_form.values() if len(v) < 15))