File size: 9,690 Bytes
6c5a14f | 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 | #!/usr/bin/env python3
"""
Run this script as ./conversion_script.py to convert FinCausal 2023's
English subtask into HF-compatible parquet files.
Citation / original source
---------------------------
Moreno-Sandoval, A., Porta-Zamorano, J., Carbajo-Coronado, B., Samy, D.,
Mariko, D., & El-Haj, M. (2023). "The Financial Document Causality
Detection Shared Task (FinCausal 2023)." 2023 IEEE International
Conference on Big Data (BigData), pp. 2855-2860. Also self-archived as
arXiv:2401.13545 (verified: Table II there reports "Train: 2949
documents; Test: 480 documents" for the English subtask -- an exact
match to the row counts fetched here, confirming this is a faithful,
complete copy of the labeled training data).
The task's OFFICIAL host is a CodaLab competition
(codalab.lisn.upsaclay.fr/competitions/14596), gated behind shared-task
registration -- unlike FinCausal 2020 (see ../FinCausal), the organizers
did not publish a plain, ungated data repo. This script instead fetches
from a shared-task PARTICIPANT's public mirror,
github.com/pavanbaswani/Fincausal_SharedTask-2023 (verified live,
public, no login) -- its `raw_data/training_subtask_en.csv` matches the
paper's own reported row count exactly, giving confidence it's a
complete, unmodified copy of the real labeled data. No LICENSE file or
terms are stated in that repo; flagged here rather than guessed at --
resolve before any redistribution beyond research use.
Only the ENGLISH subtask is converted here (the paper's own row counts
above are English-only; a separate Spanish subtask exists in the same
shared task but is not covered by this script). The repo's OWN
`raw_data/test_subtask_en.csv` is the shared task's blind test set --
verified: it has only `Index;Text` columns, no `Cause`/`Effect` at all --
so it is NOT used here. The only labeled English data anywhere is
`raw_data/training_subtask_en.csv` (2949 rows). The repo also ships a
`conll/{train,dev,test}.txt` BIO-tagged re-split of that SAME labeled
pool (verified: a spot-checked conll/test.txt segment's text is present
in training_subtask_en.csv, not in the blind test file) -- not used here
either, since re-deriving character spans from someone else's BIO
tokenization would be more failure-prone than this project's already-
proven plain substring lookup (see FinCausal 2020/PolitiCause), and
because inventing our own split (below) keeps the split logic auditable
in one place rather than depending on a third party's undocumented
random seed.
Format: semicolon-delimited CSV, `Index;Text;Cause;Effect` -- verified:
EVERY row has non-empty Cause and Effect (0/2949 empty either way), i.e.
unlike FinCausal 2020, this public release contains ONLY pre-filtered
causal segments, no non-causal ones at all. This matches Hagen et al.
2026 (arXiv:2510.08224) Table 2's own characterization of FinCausal-23
(a "-" for noncausal sentence count) -- not a gap in this conversion.
causality-DETECTION is offered here, but it's degenerate on its own: since
every segment is pre-filtered causal, the table has exactly one class (all
Causal, via causalatee.data.utils.identification_batch_to_detection on the
identification table below) -- not meaningful for training/evaluating
detection on FinCausal-23 alone, but still useful when POOLED with other
datasets' negatives for a combined detection table.
`Text` is one whole SEGMENT ("up to three sentences" per the paper),
matching FinCausal 2020/BioCause/TCR's "keep the whole multi-sentence
unit together" granularity for the same reason (cause/effect here can
span the full segment). A segment with N causal relations gets N rows
sharing one base `Index` with a ".N" suffix (verified: e.g. "1813.1813.0"
/ "1813.1813.1" for a 2-relation segment; single-relation segments use a
bare integer index instead) -- exactly the same convention as FinCausal
2020's Task 2, parsed the same way (try the bare index first is not
needed here since the base is always the part before the first ".").
Cause/Effect are given as plain substrings of Text (no character
offsets, unlike FinCausal 2020) -- located here via `str.find`, verified
0/2949 substrings failed to locate.
No train/test split exists in the only labeled file (it's one flat pool
after excluding the blind test) -- this script invents its own,
deterministic, GROUPED BY SEGMENT (never splitting a multi-relation
segment's rows across train/test) using a fixed-seed shuffle
(`random.Random(20230)`, `2023` for the shared task year + `0` so it
reads unambiguously as a seed, not a stray relation count) over the 2630
segments, ~85%/15% train/test.
"""
import random
from pathlib import Path
import pandas as pd
from causalatee.data.constants import Relation, Task
from causalatee.data.utils import identification_batch_to_detection, insert_entity_markers, verify_dataset
_TRAIN_CSV_URL = (
"https://raw.githubusercontent.com/pavanbaswani/Fincausal_SharedTask-2023"
"/main/raw_data/training_subtask_en.csv"
)
_TEST_FRACTION = 0.15
_SPLIT_SEED = 20230
def _base_index(idx: str) -> str:
return idx.split(".", 1)[0] if "." in idx else idx
def _load_segments() -> list[dict]:
"""One dict per segment: {"text", "causes": [...], "effects": [...]}."""
df = pd.read_csv(_TRAIN_CSV_URL, sep=";", dtype={"Index": str})
df["base"] = df["Index"].apply(_base_index)
segments = []
for _, group in df.groupby("base", sort=False):
segments.append({
"text": group["Text"].iloc[0],
"causes": group["Cause"].tolist(),
"effects": group["Effect"].tolist(),
})
return segments
def _split_segments() -> dict[str, list[dict]]:
segments = _load_segments()
order = list(range(len(segments)))
random.Random(_SPLIT_SEED).shuffle(order)
n_test = round(len(order) * _TEST_FRACTION)
test_idx, train_idx = set(order[:n_test]), set(order[n_test:])
return {
"train": [segments[i] for i in sorted(train_idx)],
"test": [segments[i] for i in sorted(test_idx)],
}
def convert_for_causal_candidate_extraction(split: str) -> None:
segments = _split_segments()[split]
out = []
for i, seg in enumerate(segments):
text = seg["text"]
spans = sorted({
(text.find(s), text.find(s) + len(s))
for s in seg["causes"] + seg["effects"]
})
out.append({"index": f"fincausal23_{split}_{i}", "text": text, "entity": [list(s) for s in spans]})
df = pd.DataFrame(out).set_index("index")
for error in verify_dataset(df, Task.CausalCandidateExtraction):
print(f"WARNING [FinCausal23 {Task.CausalCandidateExtraction}/{split}]: {error}")
df.to_parquet(f"./causal-candidate-extraction/{split}.parquet", engine="pyarrow")
def convert_for_causality_identification(split: str) -> None:
segments = _split_segments()[split]
out = []
for i, seg in enumerate(segments):
text = seg["text"]
span_to_id: dict[tuple[int, int], str] = {}
segment_map: dict[str, list[tuple[int, int]]] = {}
relations = []
for cause, effect in zip(seg["causes"], seg["effects"]):
ids = {}
for role, s in (("cause", cause), ("effect", effect)):
span = (text.find(s), text.find(s) + len(s))
if span not in span_to_id:
eid = f"e{len(span_to_id) + 1}"
span_to_id[span] = eid
segment_map[eid] = [span]
ids[role] = span_to_id[span]
relations.append({"relationship": Relation.Procausal, "first": ids["cause"], "second": ids["effect"]})
marked_text = insert_entity_markers(text, segment_map)
out.append({"index": f"fincausal23_{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 [FinCausal23 {Task.CausalityIdentification}/{split}]: {error}")
df.to_parquet(f"./causality-identification/{split}.parquet", engine="pyarrow")
def convert_for_causality_detection(split: str) -> None:
"""Write a causality-detection table anyway, even though it's useless
ALONE (single-class: every row is Causal, since FinCausal-23's public
data is pre-filtered causal-only -- see module docstring). Deliberately
NOT listed in docs/datasets/FinCausal23.md's ``supported_tasks`` (and
excluded from conf-causality-repro's own sweep, see that repo's
evaluation/data.py) so this project's own paper never trains/evaluates
detection on FinCausal-23 in isolation. Still written to disk so
causalatee users can pool it with other datasets' negatives for a
combined detection table, per explicit instruction.
"""
identification = pd.read_parquet(f"./causality-identification/{split}.parquet")
batch = {"text": identification["text"].tolist(), "relations": identification["relations"].tolist()}
out = identification_batch_to_detection(batch)
df = pd.DataFrame({
"index": [f"fincausal23_{split}_{i}" for i in range(len(out["text"]))],
"text": out["text"],
"label": out["label"],
}).set_index("index")
for error in verify_dataset(df, Task.CausalityDetection):
print(f"WARNING [FinCausal23 {Task.CausalityDetection}/{split}]: {error}")
Path("./causality-detection").mkdir(exist_ok=True)
df.to_parquet(f"./causality-detection/{split}.parquet", engine="pyarrow")
if __name__ == "__main__":
for split in ["train", "test"]:
convert_for_causal_candidate_extraction(split)
convert_for_causality_identification(split)
convert_for_causality_detection(split)
|