File size: 10,387 Bytes
397309c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d149dd2
397309c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3

"""
Run this script as ./conversion_script.py to convert PolitiCause DIRECTLY
from its original repository into HF-compatible parquet files.

Citation / original source
---------------------------
Garcia Corral, P., Bechara, H., Zhang, R., & Jankin, S. (2024). "PolitiCause:
An Annotation Scheme and Corpus for Causality in Political Texts." Proc. of
LREC-COLING 2024, pages 12836-12845. https://aclanthology.org/2024.lrec-main.1124/
Repo (verified live, public, no login): github.com/pgarco/PolitiCAUSE
License: CC BY-NC 4.0 (verified: the paper's own PDF header states "(c) 2024
ELRA Language Resource Association: CC BY-NC 4.0"; not restated in the repo
itself, which has no LICENSE file).

Text is drawn from two political-speech sources (paper Section 4.1): UNGD
(UN General Debate speech transcripts) and UKPress (UK government press
conference transcripts) -- not social media or parliamentary debate text.

NOTE on Hagen et al. 2026 (arXiv:2510.08224) Table 2's "implicit signals"
characterization of this dataset: the PolitiCause paper itself explicitly
disclaims implicit-causality coverage ("Our annotation scheme is not
designed to capture implicit causality..."), so that characterization
looks inconsistent with the primary source -- flagged here rather than
silently reproduced; not resolved by this script.

Two upstream files, two different granularities:

1. ``data/{train,val,test}.csv`` -- ``,text,label`` (label in {0,1}), one row
   per one of 17,780 UNIQUE sentences, already split (12446/2667/2667). This
   is the ONLY file the paper's own experiments use (three transformer
   classifiers, sentence-level causal/non-causal only -- no extraction
   results reported). Used here for causality-detection: upstream train+val
   -> causalatee train (merged, since causalatee has no dev slot -- see
   `with_validation_split` elsewhere in this toolkit), upstream test ->
   causalatee test.

2. ``data/span_annotations.csv`` -- ``,id,ra,text,spans,accept,confidence,
   label,mean_conf``, 55,754 rows over the SAME 17,780 sentences, with 2-9
   independent annotator passes per sentence (``ra`` = annotator code).
   ``label``/``text`` are identical across every row for a given ``id``
   (confirmed: this is the per-sentence GOLD, not a per-annotator opinion).
   ``accept`` is per-ANNOTATOR: whether that rater judged the sentence
   causal (with ``spans`` populated) on their individual pass -- confirmed
   real example where one rater accept=1 with real cause/effect spans,
   while the id's own gold ``label`` is 0 (the other 2 raters rejected it,
   majority/gold overruled this one rater's read). ``spans`` is a Python-
   repr'd list of single-key dicts; role keys seen: Cause, Effect (this
   project's schema), plus Subject/Connector (~10% of role-tagged spans --
   NOT part of causalatee's schema, dropped here) -- some sentences have
   MULTIPLE Cause/Effect pairs per row (up to 10 spans in one annotation).

   Since the paper never reduces these multi-rater passes to one canonical
   gold span set (it has no extraction results to need one), this script
   defines its own reconciliation policy for the causal-candidate-extraction/
   causality-identification tasks, restricted to gold-causal ids
   (label==1, 5070 of them):
     - only consider accept==1 rows (the annotator's own read agreed the
       sentence was causal);
     - among those, prefer a row with an equal, nonzero count of Cause and
       Effect spans (a "balanced" pass) over an unbalanced one, then break
       ties by that rater's own confidence rating (descending);
     - if NO accept==1 row for an id has at least one non-empty Cause AND
       one non-empty Effect at all, the id is DROPPED (461/5070 = 9.1%,
       verified: every rater on these left Cause or Effect entirely
       unmarked, e.g. [{'Cause': ''}, {'Effect': '...'}] -- a genuine
       annotation gap, not a parsing bug);
     - on the winning row, Cause spans and Effect spans are paired in
       list order, one relation per pair, truncating to
       min(#Cause, #Effect) if the winning row itself is imbalant (423/4609
       kept ids, ~9%, have exactly one extra unpaired span dropped this
       way -- a documented, minor loss, not a bug).
   Net: 4609/5070 gold-causal sentences (90.9%) end up with >=1 relation;
   4381 of those have exactly one pair, the rest 2-4.

   Span text is matched into ``text`` via plain substring search (verified:
   0/5070 chosen spans failed to locate) -- offsets are exact character
   positions of the SAME substring recorded by prodigy's annotation
   interface, which is occasionally NOT word-aligned in the source data
   itself (e.g. a real chosen span reading "atients to be better supported"
   missing its leading "P") -- an existing source-data imprecision, not
   something this script "fixes".

   ``span_annotations.csv`` has no train/val/test split of its own -- ids
   are mapped to causalatee train/test by matching each row's exact
   ``text`` against the {train,val,test}.csv split files (verified: all
   17,780 unique texts across the 3 split files match a span_annotations
   id 1:1, and every matched row's gold ``label`` agrees with its split
   file's ``label`` with 0 mismatches).
"""

import ast
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/pgarco/PolitiCAUSE/main/data"


def _fetch(fname: str) -> pd.DataFrame:
    return pd.read_csv(f"{_BASE_URL}/{fname}")


def _split_texts() -> dict[str, set[str]]:
    """causalatee split name -> set of sentence texts in that split."""
    train = pd.concat([_fetch("train.csv"), _fetch("val.csv")])
    test = _fetch("test.csv")
    return {"train": set(train["text"]), "test": set(test["text"])}


def convert_for_causality_detection(split: str) -> None:
    texts = _split_texts()[split]
    files = ["train.csv", "val.csv"] if split == "train" else ["test.csv"]
    df = pd.concat(_fetch(f) for f in files)
    df = df[df["text"].isin(texts)]
    rows = [
        {"index": f"politicause_{split}_{i}", "text": r["text"],
         "label": ClassLabel.Causal if r["label"] else ClassLabel.Uncausal}
        for i, r in enumerate(df.to_dict("records"))
    ]
    df = pd.DataFrame(rows).set_index("index")
    for error in verify_dataset(df, Task.CausalityDetection):
        print(f"WARNING [PolitiCause causality detection/{split}]: {error}")
    df.to_parquet(f"./causality-detection/{split}.parquet", engine="pyarrow")


def _reconcile_spans() -> pd.DataFrame:
    """One canonical {id, text, causes, effects} row per gold-causal id."""
    span = _fetch("span_annotations.csv")
    causal = span[span["label"] == 1].copy()
    accepted = causal[causal["accept"] == 1].copy()

    def parsed_roles(spans_repr: str) -> tuple[list[str], list[str]]:
        spans = ast.literal_eval(spans_repr)
        causes = [d["Cause"] for d in spans if "Cause" in d and d["Cause"].strip()]
        effects = [d["Effect"] for d in spans if "Effect" in d and d["Effect"].strip()]
        return causes, effects

    accepted["causes"], accepted["effects"] = zip(*accepted["spans"].apply(parsed_roles))
    accepted["usable"] = accepted["causes"].apply(len).gt(0) & accepted["effects"].apply(len).gt(0)
    accepted["imbalance"] = (accepted["causes"].apply(len) - accepted["effects"].apply(len)).abs()

    ranked = accepted.sort_values(["usable", "imbalance", "confidence"], ascending=[False, True, False])
    best = ranked.drop_duplicates("id", keep="first")
    dropped = int((~best["usable"]).sum())
    print(f"PolitiCause: dropped {dropped}/{len(best)} causal ids with no usable accept=1 Cause+Effect pair")
    return best[best["usable"]][["id", "text", "causes", "effects"]]


def convert_for_causal_candidate_extraction(split: str) -> None:
    texts = _split_texts()[split]
    reconciled = _reconcile_spans()
    reconciled = reconciled[reconciled["text"].isin(texts)]
    out = []
    for i, r in enumerate(reconciled.to_dict("records")):
        text = r["text"]
        n = min(len(r["causes"]), len(r["effects"]))
        entity = []
        for cause, effect in zip(r["causes"][:n], r["effects"][:n]):
            entity.append([text.find(cause), text.find(cause) + len(cause)])
            entity.append([text.find(effect), text.find(effect) + len(effect)])
        out.append({"index": f"politicause_{split}_{i}", "text": text, "entity": entity})
    df = pd.DataFrame(out).set_index("index")
    for error in verify_dataset(df, Task.CausalCandidateExtraction):
        print(f"WARNING [PolitiCause causal candidate extraction/{split}]: {error}")
    df.to_parquet(
        f"./causal-candidate-extraction/{split}.parquet", engine="pyarrow"
    )


def convert_for_causality_identification(split: str) -> None:
    texts = _split_texts()[split]
    reconciled = _reconcile_spans()
    reconciled = reconciled[reconciled["text"].isin(texts)]
    out = []
    for i, r in enumerate(reconciled.to_dict("records")):
        text = r["text"]
        n = min(len(r["causes"]), len(r["effects"]))
        segments: dict[str, list[tuple[int, int]]] = {}
        relations = []
        for j, (cause, effect) in enumerate(zip(r["causes"][:n], r["effects"][:n])):
            cause_id, effect_id = f"e{2 * j + 1}", f"e{2 * j + 2}"
            segments[cause_id] = [(text.find(cause), text.find(cause) + len(cause))]
            segments[effect_id] = [(text.find(effect), text.find(effect) + len(effect))]
            relations.append({"relationship": Relation.Procausal, "first": cause_id, "second": effect_id})
        marked_text = insert_entity_markers(text, segments)
        out.append({"index": f"politicause_{split}_{i}", "text": marked_text, "relations": relations})
    df = pd.DataFrame(out).set_index("index")
    for error in verify_dataset(df, Task.CausalityIdentification):
        print(f"WARNING [PolitiCause causality identification/{split}]: {error}")
    df.to_parquet(
        f"./causality-identification/{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)