CaTeRS / conversion_script.py
thagen's picture
current state
a843dd3
Raw
History Blame Contribute Delete
11.1 kB
#!/usr/bin/env python3
"""
Run this script as ./conversion_script.py to convert the CaTeRS dataset
DIRECTLY from its original brat-format annotation files, bypassing the
CREST aggregation (crest_v2.xlsx). CREST's own idx/context columns for
CaTeRS have a confirmed character-offset misalignment that corrupts
entity markup; this
script sidesteps it entirely by parsing the original brat standoff files.
Citation / original source
---------------------------
Mostafazadeh, N., Grealish, A., Chambers, N., Allen, J., & Vanderwende, L.
(2016). "CaTeRS: Causal and Temporal Relation Scheme for Semantic
Annotation of Event Structures." Proc. of the 4th Workshop on Events
(LSDSem @ EMNLP). https://aclanthology.org/W16-1007/
Data page: https://www.cs.rochester.edu/nlp/rocstories/CaTeRS/ (its brat
backend no longer serves content — verified dead as of 2026-07). The raw
.ann/.txt brat exports are mirrored, unmodified, at
github.com/phosseini/CREST, data/caters/ — verified byte-exact-correct
directly against the mirror (spot-checked several T-line offsets against
the paired .txt; no misalignment found in the RAW files themselves — the
misalignment is introduced by CREST's OWN separate aggregation script, not
present here).
Format: brat standoff (BioNLP-ST style). One .txt file with raw story
text (20 stories per file, separated by a line containing exactly "***"),
paired with a .ann file:
T<N> Event <start> <end>[;<start2> <end2>...] <surface text>
Character offsets, GLOBAL into the whole multi-story .txt file
(verified directly). ~3.4% of spans are discontinuous
(semicolon-joined segment pairs) — preserved as multi-segment entities
in the extraction task's `entity` field (see causalatee's Task docs),
and as repeated same-id <eN>...</eN> occurrences in the identification
task's marked text.
R<N> <TYPE> Arg1:T<i> Arg2:T<j>
13 relation types: 4 purely temporal (BEFORE, OVERLAPS, DURING,
IDENTITY, plus a handful of "TEMP") and 9 causal (_CAUSAL_RELATIONS
below) — matches the paper's own "9 causal + 4 temporal" framing.
Arg1 is the cause/enabler/preventer, Arg2 the effect throughout —
verified against ~20 real occurrences of ENABLE_*/PREVENT_*/
CAUSE_TO_END_* across the corpus, not just the paper's prose
description. This causal-type selection reproduces CREST's own
label==1 inclusion almost exactly (309 causal relations found here in
the train+dev+test split vs. CREST's 308 label==1 rows for CaTeRS,
off by 1) — switching source does not silently change what counts as
"causal" for this dataset.
Excludes the two IAA double-annotation files (test_15March_annot1/2.ann):
these have no paired .txt (they share the test_15Oct story text, annotated
by 4 different annotators for inter-annotator agreement) and are not
additional stories.
Known gap vs. the paper: the paper reports 320 stories; only 280 are
retrievable from this mirror (10 train batches + 3 dev parts + 1 test
file, all x20 stories). The Rochester source's live backend being dead
means the missing ~40 cannot currently be recovered. Documented, not
silently hidden.
"""
import re
import urllib.request
from pathlib import Path
import pandas as pd
from causalatee.data.constants import ClassLabel, Relation, Task
from causalatee.data.utils import insert_entity_markers, verify_dataset
_BASE_URL = "https://raw.githubusercontent.com/phosseini/CREST/master/data/caters"
_CACHE_DIR = Path(__file__).parent / ".cache"
# (subdir, filename stem) pairs per split.
_FILES: dict[str, list[tuple[str, str]]] = {
"train": [("caters_evaluation/train", f"batch_{i}") for i in range(1, 11)],
"dev": [("caters_evaluation/dev", f"part_{i}") for i in range(11, 14)],
"test": [("caters_test/test", "test_15Oct")],
}
# 9 causal relation types (of the 13 total); Arg1 = cause/enabler/preventer,
# Arg2 = effect, verified directly against real occurrences (see module
# docstring). Everything else (BEFORE, OVERLAPS, DURING, IDENTITY, TEMP) is
# purely temporal and excluded.
_CAUSAL_RELATIONS = {
"CAUSE_BEFORE", "CAUSE_OVERLAPS", "CAUSE_TO_END_BEFORE",
"CAUSE_TO_END_OVERLAP", "CAUSE_TO_END_INV_OVERLAP",
"ENABLE_BEFORE", "ENABLE_OVERLAPS", "PREVENT_BEFORE", "PREVENT_OVERLAPS",
}
def _fetch(subdir: str, stem: str, ext: str) -> str:
"""Fetch one raw file, cached locally under .cache/ (network is slow/flaky)."""
_CACHE_DIR.mkdir(parents=True, exist_ok=True)
cache_path = _CACHE_DIR / f"{stem}.{ext}"
if cache_path.exists():
return cache_path.read_text(encoding="utf-8")
url = f"{_BASE_URL}/{subdir}/{stem}.{ext}"
with urllib.request.urlopen(url) as resp:
content = resp.read().decode("utf-8")
cache_path.write_text(content, encoding="utf-8")
return content
def _parse_events(ann: str) -> dict[str, list[tuple[int, int]]]:
"""T-line id -> list of (start, end) segments (>1 entry if discontinuous)."""
events: dict[str, list[tuple[int, int]]] = {}
for line in ann.splitlines():
if not line.startswith("T"):
continue
tid, mid, _ = line.split("\t", 2)
offsets_str = mid.split(" ", 1)[1] # drop the "Event" type token
segments = [tuple(int(x) for x in pair.split()) for pair in offsets_str.split(";")]
events[tid] = sorted(segments)
return events
def _parse_causal_relations(ann: str) -> list[tuple[str, str]]:
"""List of (cause_tid, effect_tid) for every causal-typed relation."""
relations = []
for line in ann.splitlines():
if not line.startswith("R"):
continue
_, mid = line.split("\t", 1)
m = re.match(r"(\S+) Arg1:(T\d+) Arg2:(T\d+)", mid)
if not m:
continue
rtype, a1, a2 = m.groups()
if rtype in _CAUSAL_RELATIONS:
relations.append((a1, a2))
return relations
def _split_into_stories(text: str) -> list[tuple[int, int]]:
"""Global [start, end) character range per story, split on "***" lines."""
boundaries = [0] + [m.end() for m in re.finditer(r"^\*\*\*\n?", text, re.M)]
ranges = [(boundaries[i], boundaries[i + 1]) for i in range(len(boundaries) - 1)]
if boundaries[-1] < len(text):
ranges.append((boundaries[-1], len(text)))
return ranges
def _story_index(story_ranges: list[tuple[int, int]], pos: int) -> int:
for i, (s, e) in enumerate(story_ranges):
if s <= pos < e:
return i
raise ValueError(f"offset {pos} not inside any story range {story_ranges}")
def _load_stories(split: str) -> list[dict]:
"""Parse every file for a split into per-story records.
Each record: {"text": plain text (no markers), "relations": [(cause_id,
effect_id)] using local "e1","e2",... ids, "segments": {local_id:
[(start,end),...]} in story-LOCAL coordinates}.
"""
stories: list[dict] = []
for subdir, stem in _FILES[split]:
text = _fetch(subdir, stem, "txt")
ann = _fetch(subdir, stem, "ann")
events = _parse_events(ann) # global coords
causal_relations = _parse_causal_relations(ann)
story_ranges = _split_into_stories(text)
per_story_events: list[dict[str, list[tuple[int, int]]]] = [{} for _ in story_ranges]
for tid, segments in events.items():
si = _story_index(story_ranges, segments[0][0])
per_story_events[si][tid] = segments
per_story_relations: list[list[tuple[str, str]]] = [[] for _ in story_ranges]
for cause_tid, effect_tid in causal_relations:
if cause_tid not in events or effect_tid not in events:
continue
si = _story_index(story_ranges, events[cause_tid][0][0])
if _story_index(story_ranges, events[effect_tid][0][0]) != si:
continue # would indicate a parsing bug; skip defensively
per_story_relations[si].append((cause_tid, effect_tid))
for (start, end), story_events, story_relations in zip(story_ranges, per_story_events, per_story_relations):
local_text = re.sub(r"\*\*\*\n?$", "", text[start:end])
involved = sorted(
{tid for pair in story_relations for tid in pair},
key=lambda tid: story_events[tid][0][0],
)
local_id = {tid: f"e{i + 1}" for i, tid in enumerate(involved)}
segments_local = {
local_id[tid]: [(s - start, e - start) for s, e in story_events[tid]]
for tid in involved
}
relations_local = [
{"relationship": Relation.Procausal, "first": local_id[a], "second": local_id[b]}
for a, b in story_relations
]
stories.append({
"stem": stem,
"text": local_text,
"relations": relations_local,
"segments": segments_local,
})
return stories
def convert_for_causality_detection(split: str) -> None:
stories = _load_stories(split)
rows = [
{
"index": f"caters_{split}_{i}",
"text": s["text"],
"label": ClassLabel.Causal if s["relations"] else ClassLabel.Uncausal,
}
for i, s in enumerate(stories)
]
df = pd.DataFrame(rows).set_index("index")
for error in verify_dataset(df, Task.CausalityDetection):
print(f"WARNING [CaTeRS {Task.CausalityDetection}/{split}]: {error}")
df.to_parquet(f"./causality-detection/{split}.parquet", engine="pyarrow")
def convert_for_causal_candidate_extraction(split: str) -> None:
stories = _load_stories(split)
rows = []
for i, s in enumerate(stories):
entity_spans = [
[x for segment in segments for x in segment] # flatten to [s1,e1,s2,e2,...]
for segments in s["segments"].values()
]
rows.append({"index": f"caters_{split}_{i}", "text": s["text"], "entity": entity_spans})
df = pd.DataFrame(rows).set_index("index")
for error in verify_dataset(df, Task.CausalCandidateExtraction):
print(f"WARNING [CaTeRS {Task.CausalCandidateExtraction}/{split}]: {error}")
df.to_parquet(f"./causal-candidate-extraction/{split}.parquet", engine="pyarrow")
def convert_for_causality_identification(split: str) -> None:
stories = _load_stories(split)
rows = []
for i, s in enumerate(stories):
marked_text = insert_entity_markers(s["text"], s["segments"])
rows.append({"index": f"caters_{split}_{i}", "text": marked_text, "relations": s["relations"]})
df = pd.DataFrame(rows).set_index("index")
for error in verify_dataset(df, Task.CausalityIdentification):
print(f"WARNING [CaTeRS {Task.CausalityIdentification}/{split}]: {error}")
df.to_parquet(f"./causality-identification/{split}.parquet", engine="pyarrow")
if __name__ == "__main__":
for split in ["train", "dev", "test"]:
convert_for_causality_detection(split)
convert_for_causal_candidate_extraction(split)
convert_for_causality_identification(split)