File size: 3,010 Bytes
4c7afd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Recover the matched original and counterfactual rows for assignment_swaps.

Usage: python tools/reconstruct_assignment_swaps.py RECIPES.jsonl OUTPUT.jsonl
Use --source-file UPSTREAM.jsonl to read the pinned upstream file locally.
"""

import argparse
import copy
import hashlib
import json
from pathlib import Path
import re
from urllib.request import urlopen


def digest(data):
    return hashlib.sha256(data).hexdigest()


def check(expected, actual, label):
    if actual != expected:
        raise ValueError(f"{label} differs from the pinned value")


def funders_digest(funders):
    canonical = json.dumps(funders, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
    return digest(canonical.encode("utf-8"))


def reconstruct(recipe, record):
    check(recipe["doi"], record["doi"], "DOI")
    first, second = recipe["swapped_ids"]
    replacements = {first: second, second: first}
    pattern = rf"(?<!\w)(?:{re.escape(first)}|{re.escape(second)})(?!\w)"
    original = {k: record[k] for k in ("funding_statement", "funders")}
    edited = copy.deepcopy(original)
    edited["funding_statement"], changes = re.subn(
        pattern, lambda hit: replacements[hit[0]], original["funding_statement"]
    )
    check(2, changes, "number of swapped text spans")
    for funder in edited["funders"]:
        for award in funder["awards"]:
            award["award_ids"] = [replacements.get(value, value) for value in award["award_ids"]]
    for label, content in (("original", original), ("edited", edited)):
        check(recipe[f"{label}_text_sha256"], digest(content["funding_statement"].encode()), f"{label} text")
        check(recipe[f"{label}_funders_sha256"], funders_digest(content["funders"]), f"{label} funders")
    return {"id": recipe["id"], "doi": recipe["doi"], "original": original, "edited": edited,
            "swapped_ids": recipe["swapped_ids"]}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("recipes", type=Path)
    parser.add_argument("output", type=Path)
    parser.add_argument("--source-file", type=Path)
    args = parser.parse_args()
    recipes = [json.loads(line) for line in args.recipes.read_text(encoding="utf-8").splitlines()]
    sources = {(r["source_file_url"], r["source_file_sha256"]) for r in recipes}
    if len(sources) != 1:
        parser.error("supply the recipes from one split at a time")
    url, expected_hash = sources.pop()
    if args.source_file:
        raw = args.source_file.read_bytes()
    else:
        with urlopen(url, timeout=90) as response:
            raw = response.read()
    check(expected_hash, digest(raw), "upstream file SHA-256")
    lines = raw.splitlines()
    recovered = [reconstruct(r, json.loads(lines[r["source_line"] - 1])) for r in recipes]
    with args.output.open("x", encoding="utf-8") as out:
        for pair in recovered:
            out.write(json.dumps(pair, ensure_ascii=False, separators=(",", ":")) + "\n")


if __name__ == "__main__":
    main()