File size: 10,542 Bytes
4414e7d
 
 
7042254
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4414e7d
7042254
 
 
 
 
4414e7d
7042254
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4414e7d
 
7042254
 
4414e7d
7042254
 
 
 
 
4414e7d
 
7042254
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
#!/usr/bin/env python3

"""
Run this script as ./conversion_script.py to convert the TCR dataset
DIRECTLY from its original release, bypassing the CREST aggregation
(crest_v2.xlsx). CREST's own copy of TCR has a real completeness bug: 0
train rows, and its 20/5 "dev"/"test" split isn't the source's actual
train/test split at all -- see below.

Citation / original source
---------------------------
Ning, Q., Feng, Z., Wu, H., & Roth, D. (2018). "Joint Reasoning for
Temporal and Causal Relations." ACL 2018. https://aclanthology.org/P18-1212/
Repo (verified live, public, no login): https://github.com/CogComp/TCR
  - CausalPart/allClinks.txt   -- one flat TSV, all 25 documents together
  - TemporalPart/<doc_id>.tml  -- one TimeML XML file per document (this
    script only uses its inline EVENT/TIMEX3 spans and DOCID; TLINK/
    MAKEINSTANCE temporal-relation content is ignored -- irrelevant to
    causality). No LICENSE file in the repo (checked: raw-fetch of
    /LICENSE -> 404); treat as available for research use, cite the paper.

allClinks.txt format (verified: fetched directly, `wc -l` = 172, `cut -f1
| sort -u | wc -l` = 25, matching the paper's Table 3 "25 Doc, 172
C-Link" exactly): 4 tab-separated columns, no header, one causal link per
line: ``doc_id  eid_a  eid_b  relation``, ``relation`` in
{causes, caused_by} only (verified: `cut -f4 | sort -u`).
"causes" means eid_a causes eid_b; "caused_by" means eid_a is CAUSED BY
eid_b (i.e. eid_b causes eid_a) -- confirmed against real examples, e.g.
"...moussavi  e5  e6  caused_by" where e5="addressed" and e6="killed":
the killings (e6) caused the address (e5), consistent with "caused_by"'s
reading.

.tml format: standard TimeML. Events are inline ``<EVENT class="..."
eid="eN">surface text</EVENT>`` spans inside the ``<TEXT>...</TEXT>``
block; ``<TIMEX3 ...>...</TIMEX3>`` similarly marks time expressions
inline (stripped here, not used). allClinks.txt's eids join DIRECTLY
against ``<EVENT eid="...">`` -- verified against real files -- no
MAKEINSTANCE eiid indirection needed for causal links (that mapping only
matters for the temporal TLINKs this script ignores).

Train/test split: confirmed directly from the repo's own README.md,
which names exactly 5 of the 25 documents as the test set (the other 20
are, by exclusion, train) -- this is the source's real split, and it is
NOT what CREST's "dev"/"test" (20/5) buckets reproduce; CREST inverted
which split gets which name and dropped the "train" label entirely.

Granularity (see docs/datasets/TCR.md's granularity pill):
extraction and identification are WHOLE-DOCUMENT, same reasoning as
BioCause -- these are 2010 CNN news articles specifically annotated for
LONG-RANGE, cross-sentence causal reasoning (that's the paper's whole
point), so a per-sentence schema would silently drop or corrupt a large
fraction of the real annotated links. Detection, which has no natural
document-level negative class (every one of these 25 documents was
selected FOR having causal chains, so a whole-document label would
always read "causal"), is instead derived at SENTENCE granularity by
reusing causalatee.data.utils.identification_batch_to_detection_sentences
directly on this script's own whole-document identification rows -- the
exact same utility the evaluation harness uses to re-split BioCause,
applied here at conversion time instead. Only entities that participate
in an actual causal relation are marked (matching BioCause/CaTeRS/COPA's
"only causal_eids" convention) -- of ~1.3k total EVENT mentions across
the corpus, only the entities backing a real causal link are
marked/extracted.
"""

import re
import urllib.request
from pathlib import Path

import pandas as pd
import spacy

from causalatee.data.constants import ClassLabel, Relation, Task
from causalatee.data.utils import (
    identification_batch_to_detection_sentences,
    insert_entity_markers,
    verify_dataset,
)

_BASE_URL = "https://raw.githubusercontent.com/CogComp/TCR/master"
_CACHE_DIR = Path(__file__).parent / ".cache"

_TEST_DOC_IDS = {
    "2010.01.08.facebook.bra.color",
    "2010.01.12.haiti.earthquake",
    "2010.01.12.turkey.israel",
    "2010.01.13.google.china.exit",
    "2010.01.13.mexico.human.traffic.drug",
}

_TAG_RE = re.compile(r"<(/?)(EVENT|TIMEX3)\b[^>]*>")
_EID_RE = re.compile(r'eid="([^"]+)"')

_nlp = spacy.load("en_core_web_sm", disable=["ner", "lemmatizer", "tagger"])


def _fetch(rel_path: str) -> str:
    """Fetch one raw file, cached locally under .cache/."""
    _CACHE_DIR.mkdir(parents=True, exist_ok=True)
    cache_path = _CACHE_DIR / rel_path
    if cache_path.exists():
        return cache_path.read_text(encoding="utf-8")
    with urllib.request.urlopen(f"{_BASE_URL}/{rel_path}") as resp:
        content = resp.read().decode("utf-8")
    cache_path.parent.mkdir(parents=True, exist_ok=True)
    cache_path.write_text(content, encoding="utf-8")
    return content


def _parse_clinks() -> dict[str, list[tuple[str, str]]]:
    """doc_id -> list of (cause_eid, effect_eid), "causes"/"caused_by" resolved."""
    by_doc: dict[str, list[tuple[str, str]]] = {}
    for line in _fetch("CausalPart/allClinks.txt").strip().splitlines():
        doc_id, eid_a, eid_b, relation = line.split("\t")
        cause, effect = (eid_a, eid_b) if relation == "causes" else (eid_b, eid_a)
        by_doc.setdefault(doc_id, []).append((cause, effect))
    return by_doc


def _parse_tml(doc_id: str) -> tuple[str, dict[str, tuple[int, int]]]:
    """(clean_text, {eid: (start, end)}) for one document's <TEXT> block."""
    content = _fetch(f"TemporalPart/{doc_id}.tml")
    # Strip BEFORE parsing (not after): the <TEXT> block always opens with a
    # leading newline, and spans are computed relative to this exact string
    # -- stripping the joined output afterward would silently desync every
    # offset by however many characters got trimmed (caught by inspecting
    # real output: an event's marker landed one character into the word,
    # e.g. "a<e5>ddressed</e5>" instead of "<e5>addressed</e5>").
    text_block = re.search(r"<TEXT>(.*?)</TEXT>", content, re.S).group(1).strip()

    clean: list[str] = []
    spans: dict[str, tuple[int, int]] = {}
    pos = 0
    open_eid: str | None = None
    open_start = 0
    for m in _TAG_RE.finditer(text_block):
        clean.append(text_block[pos:m.start()])
        offset = sum(len(c) for c in clean)
        closing, tag = m.group(1), m.group(2)
        if tag == "EVENT":
            if closing:
                if open_eid is not None:
                    spans[open_eid] = (open_start, offset)
                open_eid = None
            else:
                eid_m = _EID_RE.search(m.group(0))
                open_eid = eid_m.group(1) if eid_m else None
                open_start = offset
        pos = m.end()
    clean.append(text_block[pos:])
    return "".join(clean), spans


def _load_documents(split: str) -> list[dict]:
    """One dict per document: {"doc_id", "text", "relations", "segments"}.

    ``relations`` uses the eid values directly as entity ids (already
    ``e<N>``-shaped, matching causalatee's marker convention);
    ``segments`` only covers eids that participate in at least one
    relation (the "only causal_eids" convention -- see module docstring).
    """
    clinks_by_doc = _parse_clinks()
    documents = []
    for doc_id, relations in clinks_by_doc.items():
        is_test = doc_id in _TEST_DOC_IDS
        if (split == "test") != is_test:
            continue
        clean_text, all_spans = _parse_tml(doc_id)
        valid_relations = [(c, e) for c, e in relations if c in all_spans and e in all_spans]
        involved = {eid for pair in valid_relations for eid in pair}
        segments = {eid: [all_spans[eid]] for eid in involved}
        documents.append({
            "doc_id": doc_id,
            "text": clean_text,
            "relations": [
                {"relationship": Relation.Procausal, "first": c, "second": e}
                for c, e in valid_relations
            ],
            "segments": segments,
        })
    return documents


def _identification_rows(split: str) -> list[dict]:
    documents = _load_documents(split)
    return [
        {
            "index": f"tcr_{split}_{i}",
            "text": insert_entity_markers(d["text"], d["segments"]) if d["segments"] else d["text"],
            "relations": d["relations"],
        }
        for i, d in enumerate(documents)
    ]


def convert_for_causal_candidate_extraction(split: str) -> None:
    documents = _load_documents(split)
    rows = []
    for i, d in enumerate(documents):
        entity = [[x for seg in d["segments"][eid] for x in seg] for eid in d["segments"]]
        rows.append({"index": f"tcr_{split}_{i}", "text": d["text"], "entity": entity})
    df = pd.DataFrame(rows).set_index("index")
    for error in verify_dataset(df, Task.CausalCandidateExtraction):
        print(f"WARNING [TCR {Task.CausalCandidateExtraction}/{split}]: {error}")
    df.to_parquet(f"./causal-candidate-extraction/{split}.parquet", engine="pyarrow")


def convert_for_causality_identification(split: str) -> None:
    df = pd.DataFrame(_identification_rows(split)).set_index("index")
    for error in verify_dataset(df, Task.CausalityIdentification):
        print(f"WARNING [TCR {Task.CausalityIdentification}/{split}]: {error}")
    df.to_parquet(f"./causality-identification/{split}.parquet", engine="pyarrow")


def _sentence_ranges(text: str) -> list[tuple[int, int]]:
    return [(s.start_char, s.end_char) for s in _nlp(text).sents]


def convert_for_causality_detection(split: str) -> None:
    ident_rows = _identification_rows(split)
    batch = {"text": [r["text"] for r in ident_rows], "relations": [r["relations"] for r in ident_rows]}
    out = identification_batch_to_detection_sentences(batch, _sentence_ranges)
    rows = [
        {"index": f"tcr_{split}_{i}", "text": text, "label": ClassLabel.Causal if label else ClassLabel.Uncausal}
        for i, (text, label) in enumerate(zip(out["text"], out["label"]))
    ]
    df = pd.DataFrame(rows).set_index("index")
    for error in verify_dataset(df, Task.CausalityDetection):
        print(f"WARNING [TCR {Task.CausalityDetection}/{split}]: {error}")
    df.to_parquet(f"./causality-detection/{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)