Datasets:
File size: 8,344 Bytes
57aeb41 cb21b69 57aeb41 cb21b69 7bc82c2 57aeb41 cad8ee2 cb21b69 57aeb41 7bc82c2 57aeb41 cb21b69 57aeb41 cb21b69 57aeb41 | 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 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 | """Convert the official DocEE English normal setting using Python's stdlib."""
import collections
import hashlib
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SOURCE = ROOT / "source"
OUT = ROOT / "dataset"
MAX_SHARD_BYTES = 4_000_000
def sha256(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def invalid_reason(row, schemas):
if not isinstance(row, list) or len(row) != 4:
return "invalid_record_structure"
title, document, event, annotations = row
for name, value in [("title", title), ("document", document), ("event_type", event)]:
if not isinstance(value, str) or not value.strip():
return "invalid_or_empty_" + name
if event not in schemas:
return "event_not_in_schema"
if not isinstance(annotations, list):
return "invalid_annotation_list"
for annotation in annotations:
if not isinstance(annotation, dict) or not {"type", "text", "start", "end"} <= annotation.keys():
return "invalid_annotation_structure"
if annotation["type"] not in schemas[event]:
return "argument_not_in_schema"
text, start, end = annotation["text"], annotation["start"], annotation["end"]
if not isinstance(text, str) or not text.strip():
return "invalid_or_empty_argument_text"
if type(start) is not int or type(end) is not int or not 0 <= start < end <= len(document):
return "invalid_argument_offsets"
if document[start:end] != text:
return "argument_offset_text_mismatch"
return None
def main():
schemas = {}
for line in (SOURCE / "Event_Schema.md").read_text().splitlines():
if line.startswith("- "):
event = line[2:].strip()
assert event not in schemas
schemas[event] = []
elif line.strip().startswith("- "):
role = line.strip()[2:].strip()
assert role not in schemas[event]
schemas[event].append(role)
assert len(schemas) == 59
(OUT / "data").mkdir(parents=True, exist_ok=True)
if list((OUT / "data").glob("*.jsonl")):
raise RuntimeError("Output already exists; use an empty data directory to rebuild.")
report = {"source_repository": "https://github.com/tongmeihan1995/DocEE",
"setting": "normal_setting", "language": "en",
"schema_sha256": sha256(SOURCE / "Event_Schema.md"),
"event_types": len(schemas), "splits": {}}
identities = {}
for original, split in [("train", "train"), ("dev", "validation"), ("test", "test")]:
path = SOURCE / "normal_setting" / (original + ".json")
source_rows = json.loads(path.read_text())
rows, dropped = [], []
for index, row in enumerate(source_rows):
reason = invalid_reason(row, schemas)
if reason:
dropped.append({"source_index": index, "reason": reason})
else:
rows.append(row)
stats = {"rows": len(rows), "annotations": 0, "null_roles": 0,
"annotated_roles": 0, "offset_mismatches": 0,
"removed_repeated_text_annotations": 0, "source_annotations_retained_rows": 0, "source_rows": len(source_rows),
"dropped_rows": dropped,
"event_counts": {}, "shards": []}
labels = collections.Counter()
identities[split] = collections.Counter()
output = None
shard_bytes = shard_rows = shard_index = 0
try:
for title, document, event, annotations in rows:
assert all(isinstance(x, str) for x in (document, event))
assert event in schemas, event
grouped = {role: [] for role in schemas[event]}
for annotation in annotations:
role, text = annotation["type"], annotation["text"]
assert role in grouped, (event, role)
assert isinstance(text, str)
grouped[role].append(text)
stats["offset_mismatches"] += document[annotation["start"]:annotation["end"]] != text
stats["source_annotations_retained_rows"] += len(annotations)
stats["removed_repeated_text_annotations"] += sum(len(v) - len(set(v)) for v in grouped.values())
grouped = {role: list(dict.fromkeys(values)) for role, values in grouped.items()}
row = {"event_trigger": title, "document": document, "event_type": event,
"arguments": [{"role": role, "values": values or None}
for role, values in grouped.items()]}
assert [a["role"] for a in row["arguments"]] == schemas[event]
assert all(len(v) == len(set(v)) for v in grouped.values())
stats["annotations"] += sum(len(v) for v in grouped.values())
stats["null_roles"] += sum(not values for values in grouped.values())
stats["annotated_roles"] += sum(bool(values) for values in grouped.values())
labels[event] += 1
identities[split][hashlib.sha256(document.encode()).hexdigest()] += 1
encoded = (json.dumps(row, ensure_ascii=False, allow_nan=False, separators=(",", ":")) + "\n").encode()
if output is None or shard_bytes + len(encoded) > MAX_SHARD_BYTES:
if output:
output.close()
stats["shards"][-1]["rows"] = shard_rows
shard_path = OUT / "data" / f"{split}-{shard_index:05d}.jsonl"
output = shard_path.open("wb")
stats["shards"].append({"path": str(shard_path.relative_to(OUT))})
shard_index += 1
shard_bytes = shard_rows = 0
output.write(encoded)
shard_bytes += len(encoded)
shard_rows += 1
finally:
if output:
output.close()
stats["shards"][-1]["rows"] = shard_rows
# Independently read each serialized row back and compare against its source.
count = 0
for shard in stats["shards"]:
shard_path = OUT / shard["path"]
shard["sha256"] = sha256(shard_path)
shard["bytes"] = shard_path.stat().st_size
for line in shard_path.read_text().split("\n"):
if not line:
continue
item = json.loads(line)
title, document, event, annotations = rows[count]
assert (item["event_trigger"], item["document"], item["event_type"]) == (title, document, event)
assert set(item) == {"event_trigger", "document", "event_type", "arguments"}
assert len(item["arguments"]) == len(schemas[event])
for role, actual in zip(schemas[event], item["arguments"]):
expected = list(dict.fromkeys(a["text"] for a in annotations if a["type"] == role)) or None
assert actual == {"role": role, "values": expected}
count += 1
assert count == len(rows)
stats["event_counts"] = dict(sorted(labels.items()))
stats["source_sha256"] = sha256(path)
stats["duplicate_documents_within_split"] = sum(n - 1 for n in identities[split].values())
report["splits"][split] = stats
print(split, {k: v for k, v in stats.items() if k not in ("event_counts", "shards")})
report["document_overlap_between_splits"] = {
a + "/" + b: len(set(identities[a]) & set(identities[b]))
for a, b in [("train", "validation"), ("train", "test"), ("validation", "test")]}
report["validation"] = "Malformed source rows are dropped, not repaired. All serialized rows match retained source titles, documents, labels, schema roles and unique argument texts per role in first-occurrence order. Exact duplicate texts within each document and role are removed."
for name, data in [("schemas.json", schemas), ("validation_report.json", report)]:
(OUT / name).write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n")
print("Overlap:", report["document_overlap_between_splits"])
if __name__ == "__main__":
main()
|