TCR / conversion_script.py
thagen's picture
current state
7042254
Raw
History Blame Contribute Delete
10.5 kB
#!/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)