"""Resolve authored training pairs and focal development examples from a local split. Usage: python resolve_assignment_data.py train.jsonl --output pairs.jsonl For an offline training run, add --source-file PATH_TO_UPSTREAM_FULL_TRAIN_JSONL. """ import argparse import hashlib import json from functools import lru_cache from pathlib import Path from urllib.request import Request, urlopen def digest(value): if isinstance(value, str): value = value.encode("utf-8") return hashlib.sha256(value).hexdigest() def checked(value, expected): if digest(value) != expected: raise ValueError(f"Source content differs from frozen SHA-256 {expected}") return value @lru_cache(maxsize=8) def source_bytes(url, expected, local_file): if local_file: content = Path(local_file).read_bytes() else: request = Request(url, headers={"User-Agent": "COMET-assignment-data/1"}) with urlopen(request, timeout=45) as response: content = response.read() return checked(content, expected) @lru_cache(maxsize=4) def jsonl_records(url, expected, local_file): return [json.loads(line) for line in source_bytes(url, expected, local_file).splitlines()] def source_passage(source, local_file=None): kind = source["format"] args = (source["file_url"], source["file_sha256"], local_file) if kind == "jsonl": record = jsonl_records(*args)[source["row_index"]] text = record[source["field"]] elif kind == "jats_xml": from lxml import etree root = etree.fromstring(source_bytes(*args)) node, = root.xpath(source["xpath"]) text = " ".join("".join(node.itertext()).split()) else: raise ValueError(f"Consult the paper locator to recover this passage: {source['locator']}") original = text[source["start"]:source["end"]] return checked(original, source["passage_sha256"]) def apply_edits(original, edits): text = original for edit in reversed(edits): text = text[:edit["start"]] + edit["replacement"] + text[edit["end"]:] return text def resolve(row, local_file=None): if "edited_funders" in row: original = source_passage(row["source"], local_file) edited = checked(apply_edits(original, row["edits"]), row["edited_sha256"]) for variant, text in [("original", original), ("edited", edited)]: yield { "id": row["id"], "focus": row["focus"], "variant": variant, "funding_statement": text, "funders": row[f"{variant}_funders"], } return if "funding_statement" not in row: raise ValueError("Expected an assignment_training or assignment_development split") text = row["funding_statement"] if text is None and row["source"]["format"] in {"jsonl", "jats_xml"}: text = apply_edits(source_passage(row["source"], local_file), row["edits"] or []) if text is not None: checked(text, row["funding_statement_sha256"]) yield dict(row, funding_statement=text) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("split", type=Path, help="a local JSONL split") parser.add_argument("--source-file", type=Path, help="for a split that uses one frozen source") parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() rows = [json.loads(line) for line in args.split.read_text(encoding="utf-8").splitlines()] output = [result for row in rows for result in resolve(row, args.source_file)] with args.output.open("w", encoding="utf-8") as stream: for row in output: stream.write(json.dumps(row, ensure_ascii=False) + "\n") print(f"Wrote {len(output)} records") if __name__ == "__main__": main()