Datasets:
Download scripts/prepare_dataset.py from meihant/DocEE: direct link, hf CLI and curl.
- Browser
- Download file 8.34 kB
-
https://huggingface.co/datasets/meihant/DocEE/resolve/main/scripts/prepare_dataset.py
- Command line
-
hf download hf://datasets/meihant/DocEE/scripts/prepare_dataset.py
-
curl -L -o prepare_dataset.py https://huggingface.co/datasets/meihant/DocEE/resolve/main/scripts/prepare_dataset.py
8.34 kB
| """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() | |