File size: 12,898 Bytes
cf916ef
 
 
6a82406
cf916ef
6a82406
 
 
 
 
 
 
 
cf916ef
6a82406
 
 
cf916ef
6a82406
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf916ef
6a82406
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf916ef
6a82406
 
 
 
 
 
 
 
cf916ef
6a82406
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf916ef
 
 
 
 
6a82406
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
#!/usr/bin/env python3

"""
Direct converter from EventStoryLine (ECB+ XML) to HF-compatible parquet files.

Source XML: https://github.com/tommasoc80/EventStoryLine (v1.0, annotated_data/)
Train/test split: topic-based, matching the UniCausal esl2 split so that model
  comparisons remain valid (topics 37 and 41 → test; all others → train).

This replaces the previous UniCausal-CSV-based conversion, which contained
malformed text_w_pairs for ~642 rows due to a char-offset tracking bug in
UniCausal's tag insertion code when event spans overlap.  The direct ECB+ XML
parser below never constructs tags via character offsets and is not affected.

API note: ESL2HF mirrors the UniCausal2HF constructor signature so the class
  can be moved into causalatee.data.conversion in the future without changes to call
  sites.

No causal-candidate-extraction table: ESL2HF only implements detection and
identification (see its ``_convert``). Derived instead from the
causality-identification table written below, via
causalatee.data.utils.identification_batch_to_extraction -- keeps the two
tables consistent by construction. Note ESL's own ``relations`` explicitly
records a ``Relation.NoRelation`` entry for every non-causal event pair
(see ``_build_sentence_rows`` below) rather than omitting it, same as
CTB/SemEval2010T8 -- identification_batch_to_extraction filters those out
rather than treating "relations list non-empty" as causal.

Dependencies: pip install causalatee  (brings in lxml via pyarrow transitively;
  stdlib xml.etree.ElementTree is used here to avoid extra deps)
"""

import io
import urllib.request
from collections import defaultdict
from pathlib import Path
from xml.etree import ElementTree as ET

import pandas as pd

from causalatee.data.constants import ClassLabel, Relation, Task
from causalatee.data.conversion._converter import FormatConverter
from causalatee.data.utils import identification_batch_to_extraction


# ---------------------------------------------------------------------------
# ECB+ XML constants
# ---------------------------------------------------------------------------

_CAUSAL_REL_TYPES = frozenset({"PRECONDITION", "FALLING_ACTION"})

# All ECB+ event markable types (excludes entity/time/signal types)
_EVENT_MARKABLE_TAGS = frozenset({
    "ACTION_OCCURRENCE",
    "ACTION_STATE",
    "ACTION_ASPECTUAL",
    "ACTION_PERCEPTION",
    "ACTION_REPORTING",
    "NEG_ACTION_OCCURRENCE",
    "NEG_ACTION_STATE",
    "NEG_ACTION_ASPECTUAL",
})

_ESL_RAW_BASE = (
    "https://raw.githubusercontent.com/tommasoc80/EventStoryLine"
    "/master/annotated_data/v1.0"
)
_UNICAUSAL_BASE = (
    "https://raw.githubusercontent.com/tanfiona/UniCausal"
    "/refs/heads/main/data/splits"
)


# ---------------------------------------------------------------------------
# ECB+ XML parsing
# ---------------------------------------------------------------------------

def _fetch_xml(url_or_path: str) -> ET.Element:
    if url_or_path.startswith("http://") or url_or_path.startswith("https://"):
        with urllib.request.urlopen(url_or_path) as r:
            return ET.fromstring(r.read())
    return ET.parse(url_or_path).getroot()


def _parse_doc(url_or_path: str) -> dict:
    """Parse one ECB+ XML file; return structured token/event/relation data."""
    root = _fetch_xml(url_or_path)
    doc_name = root.attrib.get("doc_name", Path(url_or_path).stem)

    # t_id → (sent_id, within-sentence position, word)
    tok_info: dict[int, tuple[int, int, str]] = {}
    for tok in root.iter("token"):
        tok_info[int(tok.attrib["t_id"])] = (
            int(tok.attrib["sentence"]),
            int(tok.attrib["number"]),
            tok.text or "",
        )

    # Event markables: m_id → sorted list of t_ids.
    # Exclude multi-sentence events (span can't be represented in one row).
    events: dict[int, list[int]] = {}
    markables = root.find("Markables")
    if markables is not None:
        for mark in markables:
            if mark.tag not in _EVENT_MARKABLE_TAGS:
                continue
            m_id = int(mark.attrib["m_id"])
            t_ids = sorted(int(a.attrib["t_id"]) for a in mark.findall("token_anchor"))
            if not t_ids:
                continue
            sents = {tok_info[t][0] for t in t_ids if t in tok_info}
            if len(sents) == 1:
                events[m_id] = t_ids

    # PLOT_LINK causal pairs: both PRECONDITION and FALLING_ACTION are causal.
    # Only retain pairs where both events are single-sentence (in `events`).
    causal_pairs: set[tuple[int, int]] = set()
    relations_elem = root.find("Relations")
    if relations_elem is not None:
        for rel in relations_elem.findall("PLOT_LINK"):
            if rel.attrib.get("relType", "") not in _CAUSAL_REL_TYPES:
                continue
            src = rel.find("source")
            tgt = rel.find("target")
            if src is None or tgt is None:
                continue
            sm, tm = int(src.attrib["m_id"]), int(tgt.attrib["m_id"])
            if sm in events and tm in events:
                causal_pairs.add((sm, tm))

    return {
        "doc_name": doc_name,
        "tok_info": tok_info,
        "events": events,
        "causal_pairs": causal_pairs,
    }


def _build_sentence_rows(parsed: dict) -> list[dict]:
    """Yield one row per sentence that contains at least two event markables."""
    tok_info = parsed["tok_info"]
    events = parsed["events"]
    causal_pairs = parsed["causal_pairs"]
    doc_name = parsed["doc_name"]

    # Group events by sentence; sentence 0 is the URL/header line in ECB+.
    sent_to_mids: dict[int, list[int]] = defaultdict(list)
    for m_id, t_ids in events.items():
        sid = tok_info[t_ids[0]][0]
        if sid > 0:
            sent_to_mids[sid].append(m_id)

    # Build sorted token list per sentence (skip sentence 0).
    sent_toks: dict[int, list[tuple[int, str]]] = defaultdict(list)
    for t_id, (sid, pos, word) in tok_info.items():
        if sid > 0:
            sent_toks[sid].append((pos, word))
    for toks in sent_toks.values():
        toks.sort()

    rows = []
    for sent_id, m_ids in sent_to_mids.items():
        if len(m_ids) < 2 or sent_id not in sent_toks:
            continue

        tok_list = sent_toks[sent_id]
        text = " ".join(w for _, w in tok_list)

        # Within-sentence token positions per event.
        m_positions: dict[int, list[int]] = {}
        for m_id in m_ids:
            positions = sorted(
                tok_info[t][1] for t in events[m_id] if tok_info[t][0] == sent_id
            )
            if positions:
                m_positions[m_id] = positions

        # Sort events by first token position; assign 1-indexed entity IDs.
        m_ids_sorted = sorted(m_positions, key=lambda m: m_positions[m][0])
        eid_map = {m: i + 1 for i, m in enumerate(m_ids_sorted)}

        # Entity-marked text: open tag at first token, close tag at last token.
        # Overlapping spans (two events sharing tokens) are handled naturally:
        # the inner entity's open/close tags are inserted within the outer one.
        starts_at: dict[int, list[int]] = defaultdict(list)
        ends_at: dict[int, list[int]] = defaultdict(list)
        for m_id, positions in m_positions.items():
            eid = eid_map[m_id]
            starts_at[positions[0]].append(eid)
            ends_at[positions[-1]].append(eid)

        marked_parts = []
        for pos, word in tok_list:
            opens = "".join(f"<e{e}>" for e in sorted(starts_at.get(pos, [])))
            closes = "".join(
                f"</e{e}>" for e in sorted(ends_at.get(pos, []), reverse=True)
            )
            marked_parts.append(opens + word + closes)
        marked_text = " ".join(marked_parts)

        # All ordered pairs of events in this sentence, labeled by PLOT_LINK.
        relations = []
        for i, ma in enumerate(m_ids_sorted):
            for mb in m_ids_sorted[i + 1:]:
                ea, eb = f"e{eid_map[ma]}", f"e{eid_map[mb]}"
                for src, tgt, es, et in [(ma, mb, ea, eb), (mb, ma, eb, ea)]:
                    rel = (
                        Relation.Procausal
                        if (src, tgt) in causal_pairs
                        else Relation.NoRelation
                    )
                    relations.append({"relationship": rel, "first": es, "second": et})

        rows.append({
            "index": f"esl_{doc_name}_{sent_id}",
            "text": text,
            "marked_text": marked_text,
            "relations": relations,
            "causal": any(r["relationship"] == Relation.Procausal for r in relations),
        })

    return rows


# ---------------------------------------------------------------------------
# Converter class (mirrors UniCausal2HF API)
# ---------------------------------------------------------------------------

class ESL2HF(FormatConverter):
    """Convert EventStoryLine ECB+ XML files directly to causalatee parquet.

    Args:
        splits: mapping from split name (``"train"``, ``"test"``, …) to a list
            of ECB+ XML file URLs or local paths for that split.
        target: directory where task-named subdirectories and parquet files
            are written (same semantics as ``UniCausal2HF``).
    """

    def __init__(self, splits: dict[str, list[str]], target: Path):
        super().__init__(target)
        self._splits = splits

    def _load_rows(self, split: str) -> list[dict]:
        rows = []
        for url_or_path in self._splits[split]:
            try:
                parsed = _parse_doc(url_or_path)
            except Exception as exc:
                print(f"  [skip] {url_or_path}: {exc}")
                continue
            rows.extend(_build_sentence_rows(parsed))
        return rows

    def _convert(self, task: str, split: str) -> pd.DataFrame:
        rows = self._load_rows(split)
        if task == Task.CausalityDetection:
            return self._convert_detection(rows)
        if task == Task.CausalityIdentification:
            return self._convert_identification(rows)
        raise ValueError(f"ESL2HF does not support task {task!r}")

    def _convert_detection(self, rows: list[dict]) -> pd.DataFrame:
        data = [
            {
                "index": r["index"],
                "label": ClassLabel.Causal if r["causal"] else ClassLabel.Uncausal,
                "text": r["text"],
            }
            for r in rows
        ]
        return pd.DataFrame(data).set_index("index")

    def _convert_identification(self, rows: list[dict]) -> pd.DataFrame:
        data = [
            {
                "index": r["index"],
                "text": r["marked_text"],
                "relations": r["relations"],
            }
            for r in rows
        ]
        return pd.DataFrame(data).set_index("index")


# ---------------------------------------------------------------------------
# Script body
# ---------------------------------------------------------------------------

def _doc_id_to_url(doc_id: str) -> str:
    """Map a UniCausal doc_id (e.g. '1_10ecbplus.xml.xml') to its GitHub URL."""
    topic = doc_id.split("_")[0]
    return f"{_ESL_RAW_BASE}/{topic}/{doc_id}"


def _get_split_doc_ids(unicausal_csv_url: str) -> list[str]:
    with urllib.request.urlopen(unicausal_csv_url) as r:
        df = pd.read_csv(io.BytesIO(r.read()))
    return df["doc_id"].unique().tolist()


print("Fetching UniCausal split document lists...")
train_doc_ids = _get_split_doc_ids(f"{_UNICAUSAL_BASE}/esl2_train.csv")
test_doc_ids = _get_split_doc_ids(f"{_UNICAUSAL_BASE}/esl2_test.csv")
print(f"  train: {len(train_doc_ids)} documents")
print(f"  test:  {len(test_doc_ids)} documents")

converter = ESL2HF(
    splits={
        "train": [_doc_id_to_url(d) for d in train_doc_ids],
        "test": [_doc_id_to_url(d) for d in test_doc_ids],
    },
    target=Path.cwd(),
)

converter.convert(Task.CausalityDetection, "train")
converter.convert(Task.CausalityDetection, "test")
converter.convert(Task.CausalityIdentification, "train")
converter.convert(Task.CausalityIdentification, "test")


def _convert_extraction_from_identification(split: str) -> None:
    identification = pd.read_parquet(f"./causality-identification/{split}.parquet")
    batch = {"text": identification["text"].tolist(), "relations": identification["relations"].tolist()}
    out = identification_batch_to_extraction(batch)
    df = pd.DataFrame({
        "index": [f"esl_{split}_{i}" for i in range(len(out["text"]))],
        "text": out["text"],
        "entity": out["entity"],
    }).set_index("index")
    Path("./causal-candidate-extraction").mkdir(exist_ok=True)
    df.to_parquet(f"./causal-candidate-extraction/{split}.parquet", engine="pyarrow")


_convert_extraction_from_identification("train")
_convert_extraction_from_identification("test")