EventStoryLine / conversion_script.py
thagen's picture
current state
6a82406
Raw
History Blame Contribute Delete
12.9 kB
#!/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")