| |
|
|
| """ |
| Run this script as ./conversion_script.py to convert the Cause-Effect |
| relation subset of SemEval-2007 Task 4 ("Classification of Semantic |
| Relations between Nominals") into HF-compatible parquet files. |
| |
| Citation / original source |
| --------------------------- |
| Girju, R., Hearst, M., Nakov, P., Nastase, V., Szpakowicz, S., Turney, P., |
| & Yuret, D. (2007). "SemEval-2007 Task 04: Classification of Semantic |
| Relations between Nominals." Proceedings of the 4th International |
| Workshop on Semantic Evaluations (SemEval-2007), pages 13-18. |
| https://aclanthology.org/S07-1003/ |
| License: CC BY-SA 2.5 (verified: the dataset's own bundled |
| `copyright.txt` states "The Complete Dataset and the Trial Dataset for |
| Task 4 are released under the Creative Commons Attribution-Share Alike |
| 2.5 License"). |
| |
| The task covers SEVEN semantic relations between nominal pairs |
| (Cause-Effect, Instrument-Agency, Product-Producer, Origin-Entity, |
| Theme-Tool, Part-Whole, Content-Container), one file per relation |
| (``relation-1`` .. ``relation-7``); only relation-1 (verified directly |
| by reading its own definition PDF: "Cause-Effect") is used here. |
| |
| Repo (verified live, public, no login, byte-identical to the original |
| archive -- diffed relation-1's train/test/key files directly against a |
| copy fetched from the official SemEval-2007 distribution before trusting |
| it): github.com/davidsbatista/Annotated-Semantic-Relationships-Datasets, |
| ``datasets/SemEval2007-Task4.tar.gz`` (a plain, uncompressed POSIX tar |
| despite the ``.tar.gz`` name -- verified via ``file``), containing |
| nested ``train.tar.gz``/``test.tar.gz``/``key.tar.gz``. |
| |
| Format: each relation file is a sequence of blank-line-separated records: |
| ``NNN "sentence with <e1>...</e1> and <e2>...</e2> markers"`` |
| ``WordNet(e1) = "...", WordNet(e2) = "...", Cause-Effect(eX,eY) = "true"/"false"/"?", Query = "..."`` |
| optionally followed by a ``Comment:`` line. |
| The ``<e1>``/``<e2>`` markers are ALREADY in this project's own marker |
| format (verified: `causalatee.data.utils.parse_entity_markers` parses |
| them directly with no preprocessing). The ``Cause-Effect(eX,eY)`` |
| argument order gives the (cause, effect) role assignment for THAT |
| record -- verified this is NOT fixed: 130/140 train records use |
| ``(e2,e1)`` but 10/140 use ``(e1,e2)`` (e.g. record 011: |
| "<e1>Zinc</e1> is essential for <e2>growth</e2>", Cause-Effect(e1,e2) -- |
| zinc causes growth, e1 IS the cause here), so the parser reads the |
| argument order per record rather than assuming a fixed e2->e1 direction. |
| |
| Train (140 records, real true/false labels inline) and test (80 records, |
| label hidden as "?" in ``test/relation-1-test.txt``) are SEPARATE files; |
| test's real gold labels live in a third file, ``key/relation-1-score.txt`` |
| -- verified: matched 1:1 by record index against test's own text/entity- |
| direction with 0 mismatches across all 80 test records. Total 220 |
| records (114 true / 106 false) -- note Hagen et al. 2026 (arXiv:2510.08224) |
| Table 2 cites this as "220 causal + 114 noncausal": 220 is actually the |
| TOTAL record count here, and 114 matches this project's own CAUSAL count, |
| not noncausal (106) -- looks like a mislabeling in that table (total |
| mistaken for the causal count, or causal/noncausal swapped), not a |
| mismatch in this conversion; flagged rather than silently reproduced. |
| |
| causality-detection uses all 220 records (label = causal iff true). |
| causal-candidate-extraction/causality-identification use only the 114 |
| causal (true) records for their entity/relation content -- matching this |
| project's established convention elsewhere (e.g. BioCause, FinCausal) of |
| only extracting spans that back an actual relation; the 106 false records |
| still appear in causality-identification (entities marked, empty |
| relations list) so the evaluation harness's own pair-flattening can |
| derive negative pairs from them, exactly as for every other dataset here. |
| """ |
|
|
| import io |
| import re |
| import tarfile |
| import urllib.request |
| from pathlib import Path |
|
|
| import pandas as pd |
|
|
| from causalatee.data.constants import ClassLabel, Relation, Task |
| from causalatee.data.utils import parse_entity_markers, verify_dataset |
|
|
| _TAR_URL = ( |
| "https://raw.githubusercontent.com/davidsbatista/Annotated-Semantic-Relationships-Datasets" |
| "/master/datasets/SemEval2007-Task4.tar.gz" |
| ) |
| _CACHE_DIR = Path(__file__).parent / ".cache" |
|
|
| _RECORD_RE = re.compile(r'^(\d+)\s+"(.*)"\s*$') |
| _LABEL_RE = re.compile(r'Cause-Effect\((e\d),(e\d)\)\s*=\s*"([^"]*)"') |
|
|
|
|
| def _fetch_files() -> dict[str, str]: |
| """Download+extract once (cached); return {"train": ..., "test": ..., "key": ...} raw text.""" |
| _CACHE_DIR.mkdir(parents=True, exist_ok=True) |
| out = {} |
| for name in ["train", "test", "key"]: |
| cache_path = _CACHE_DIR / f"relation-1-{name}.txt" |
| if cache_path.exists(): |
| out[name] = cache_path.read_text(encoding="latin-1") |
| continue |
| with urllib.request.urlopen(_TAR_URL) as resp: |
| outer = tarfile.open(fileobj=io.BytesIO(resp.read())) |
| inner_name = {"train": "train.tar.gz", "test": "test.tar.gz", "key": "key.tar.gz"}[name] |
| inner_bytes = outer.extractfile(f"SemEval2007-Task4/{inner_name}").read() |
| inner = tarfile.open(fileobj=io.BytesIO(inner_bytes)) |
| fname = {"train": "train/relation-1-train.txt", "test": "test/relation-1-test.txt", |
| "key": "key/relation-1-score.txt"}[name] |
| text = inner.extractfile(fname).read().decode("latin-1") |
| cache_path.write_text(text, encoding="latin-1") |
| out[name] = text |
| return out |
|
|
|
|
| def _parse_records(text: str) -> dict[str, dict]: |
| """idx -> {"text": marked sentence, "cause_ref": "e1"|"e2", "effect_ref": ..., "label": "true"/"false"/"?"}.""" |
| records = {} |
| for block in re.split(r"\n\s*\n", text.strip()): |
| lines = block.strip().splitlines() |
| if not lines: |
| continue |
| m = _RECORD_RE.match(lines[0]) |
| if not m: |
| continue |
| idx, sent = m.groups() |
| rel_line = lines[1] if len(lines) > 1 else "" |
| lm = _LABEL_RE.search(rel_line) |
| if not lm: |
| continue |
| cause_ref, effect_ref, label = lm.groups() |
| records[idx] = {"text": sent, "cause_ref": cause_ref, "effect_ref": effect_ref, "label": label} |
| return records |
|
|
|
|
| def _load_split(split: str) -> dict[str, dict]: |
| """causalatee split name -> {idx: record} with resolved true/false labels.""" |
| files = _fetch_files() |
| if split == "train": |
| return _parse_records(files["train"]) |
| test_records = _parse_records(files["test"]) |
| key_records = _parse_records(files["key"]) |
| for idx, rec in test_records.items(): |
| rec["label"] = key_records[idx]["label"] |
| return test_records |
|
|
|
|
| def convert_for_causality_detection(split: str) -> None: |
| records = _load_split(split) |
| rows = [] |
| for idx, rec in records.items(): |
| clean_text, _ = parse_entity_markers(rec["text"]) |
| label = ClassLabel.Causal if rec["label"] == "true" else ClassLabel.Uncausal |
| rows.append({"index": f"semeval2007t4_{split}_{idx}", "text": clean_text, "label": label}) |
| df = pd.DataFrame(rows).set_index("index") |
| for error in verify_dataset(df, Task.CausalityDetection): |
| print(f"WARNING [SemEval2007T4 causality detection/{split}]: {error}") |
| df.to_parquet(f"./causality-detection/{split}.parquet", engine="pyarrow") |
|
|
|
|
| def convert_for_causal_candidate_extraction(split: str) -> None: |
| records = _load_split(split) |
| out = [] |
| for idx, rec in records.items(): |
| if rec["label"] != "true": |
| continue |
| clean_text, segments = parse_entity_markers(rec["text"]) |
| entity = sorted(seg for segs in segments.values() for seg in segs) |
| out.append({"index": f"semeval2007t4_{split}_{idx}", "text": clean_text, "entity": [list(s) for s in entity]}) |
| df = pd.DataFrame(out).set_index("index") |
| for error in verify_dataset(df, Task.CausalCandidateExtraction): |
| print(f"WARNING [SemEval2007T4 causal candidate extraction/{split}]: {error}") |
| df.to_parquet( |
| f"./causal-candidate-extraction/{split}.parquet", engine="pyarrow" |
| ) |
|
|
|
|
| def convert_for_causality_identification(split: str) -> None: |
| records = _load_split(split) |
| out = [] |
| for idx, rec in records.items(): |
| clean_text, segments = parse_entity_markers(rec["text"]) |
| relations = [] |
| if rec["label"] == "true": |
| relations.append({ |
| "relationship": Relation.Procausal, |
| "first": rec["cause_ref"], |
| "second": rec["effect_ref"], |
| }) |
| out.append({"index": f"semeval2007t4_{split}_{idx}", "text": rec["text"], "relations": relations}) |
| df = pd.DataFrame(out).set_index("index") |
| for error in verify_dataset(df, Task.CausalityIdentification): |
| print(f"WARNING [SemEval2007T4 causality identification/{split}]: {error}") |
| df.to_parquet( |
| f"./causality-identification/{split}.parquet", engine="pyarrow" |
| ) |
|
|
|
|
| if __name__ == "__main__": |
| for split in ["train", "test"]: |
| convert_for_causality_detection(split) |
| convert_for_causal_candidate_extraction(split) |
| convert_for_causality_identification(split) |
|
|