File size: 9,196 Bytes
bc1c1c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3

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

Citation / original source
---------------------------
Mariko, D., Abi Akl, H., Labidurie, E., Durand, S., Sugawara, H.,
Mansar, Y., & El-Haj, M. (2020). "The Financial Document Causality
Detection Shared Task (FinCausal 2020)." Proc. of the 1st Joint
Workshop on Financial Narrative Processing and MultiLing Financial
Summarisation (FNP 2020). https://aclanthology.org/2020.fnp-1.3/
Repo (verified live, public, no login): github.com/yseop/YseopLab,
branch ``develop``, directory ``FNP_2020_FinCausal/`` (the shared task
organizers' own repo -- cited directly in the paper's own footnotes for
baseline/scoring code; a sibling participant repo,
github.com/guillaume-be/Financial-Causality-Extraction, was checked and
is NOT a data host, just a competing system).
License: CC0 (verified: the paper's own text states "Data are released
under the CC0 License").

Only "trial" and "practice" (= "Training" per the paper's own prose,
despite the folder being named "practice") have gold labels --
"evaluation" is the blind shared-task test set (verified: its
task1_blind.csv/task2_blind.csv have no Gold/Cause/Effect columns at
all, and no labeled version was ever republished here). Mapped as:
practice ("Training") -> causalatee train, trial -> causalatee test; no
dev.parquet (`with_validation_split` in the evaluation harness carves
one out of train automatically).

Format: semicolon-delimited CSV, one row per whole TEXT SECTION (a
multi-sentence excerpt, not a single sentence -- matches the paper's own
"text sections" framing, e.g. 13478 sections in "practice"). Causal
relations, when present, can genuinely span MULTIPLE sentences within
one section (verified on real rows: a 3-sentence section with cause and
effect each being one whole sentence) -- the same "keep the whole
multi-sentence unit, don't force it into one sentence" granularity this
project already uses for BioCause/TCR, for the same reason: splitting
would risk dropping or corrupting genuinely
cross-sentence relations.
  Task 1 (``*-task1.csv``): ``Index; Text; Gold`` -- Gold in {0, 1},
    ALL text sections (causal and not).
  Task 2 (``*-task2.csv``): ``Index; Text; Cause; Effect;
    Offset_Sentence2; Offset_Sentence3; Cause_Start; Cause_End;
    Effect_Start; Effect_End; Sentence`` -- ONLY causal sections. A
    section with N causal relations gets N rows sharing the same base
    Index with a ".1", ".2", ... suffix (verified: single-relation
    sections instead reuse task1's bare index with NO suffix at all --
    this script resolves Task 2's ``Index`` against Task 1 by trying the
    bare value FIRST, falling back to stripping a trailing ``.N``, since
    assuming every Task-2 index has a suffix is wrong and silently
    mismatches ~93% of rows against Task 1's Text).
  Cause_Start/Cause_End are a standard Python-style HALF-OPEN
    ``text[start:end]`` span into the section's ``Text`` -- verified: 0
    mismatches against the ``Cause`` column across every row checked (both
    splits). Effect_Start/Effect_End are, unusually, CLOSED on both ends
    (need ``text[start:end+1]``) -- verified: this fits ~96% of rows
    exactly; the remaining ~4% are off by one character either way (a
    genuine annotation-offset inconsistency in the source itself, not a
    parsing bug here -- inspected several real examples, e.g. an
    Effect span landing on "...below 108," instead of "...below 108"),
    accepted as a small, documented source-data imperfection rather than
    something this script can resolve.
"""

import csv
import io
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/yseop/YseopLab/develop/FNP_2020_FinCausal/data"
_CACHE_DIR = Path(__file__).parent / ".cache"

# causalatee split name -> (upstream dir, task1 filename, task2 filename).
# "practice"'s file names include a "2" (2nd annotation round) that
# "trial"'s do not -- verified directly, not a typo.
_SPLITS = {
    "train": ("practice", "fnp2020-fincausal2-task1.csv", "fnp2020-fincausal2-task2.csv"),
    "test": ("trial", "fnp2020-fincausal-task1.csv", "fnp2020-fincausal-task2.csv"),
}


def _fetch(subdir: str, fname: str) -> list[dict]:
    """Fetch+parse one raw semicolon-delimited CSV, cached under .cache/."""
    _CACHE_DIR.mkdir(parents=True, exist_ok=True)
    cache_path = _CACHE_DIR / subdir / fname
    if cache_path.exists():
        content = cache_path.read_text(encoding="utf-8")
    else:
        with urllib.request.urlopen(f"{_BASE_URL}/{subdir}/{fname}") as resp:
            content = resp.read().decode("utf-8-sig")
        cache_path.parent.mkdir(parents=True, exist_ok=True)
        cache_path.write_text(content, encoding="utf-8")
    reader = csv.DictReader(io.StringIO(content), delimiter=";")
    return [{k.strip(): (v.strip() if isinstance(v, str) else v) for k, v in row.items()} for row in reader]


def _load_task1(split: str) -> dict[str, str]:
    """index -> whole-section text, for every section (causal or not)."""
    subdir, task1_fname, _ = _SPLITS[split]
    return {r["Index"]: r["Text"] for r in _fetch(subdir, task1_fname)}


def _load_relations_by_index(split: str) -> dict[str, list[dict]]:
    """base task1 index -> list of {"cause": (s,e), "effect": (s,e)}."""
    subdir, _, task2_fname = _SPLITS[split]
    task1_texts = _load_task1(split)
    by_index: dict[str, list[dict]] = {}
    for r in _fetch(subdir, task2_fname):
        idx = r["Index"]
        base = idx if idx in task1_texts else idx.rsplit(".", 1)[0]
        if base not in task1_texts:
            continue  # would indicate a genuinely unresolvable index; not seen in practice
        cs, ce = int(r["Cause_Start"]), int(r["Cause_End"])
        es, ee = int(r["Effect_Start"]), int(r["Effect_End"])
        by_index.setdefault(base, []).append({"cause": (cs, ce), "effect": (es, ee + 1)})
    return by_index


def convert_for_causality_detection(split: str) -> None:
    subdir, task1_fname, _ = _SPLITS[split]
    rows = [
        {"index": f"fincausal20_{split}_{r['Index']}", "text": r["Text"],
         "label": ClassLabel.Causal if int(r["Gold"]) else ClassLabel.Uncausal}
        for r in _fetch(subdir, task1_fname)
    ]
    df = pd.DataFrame(rows).set_index("index")
    for error in verify_dataset(df, Task.CausalityDetection):
        print(f"WARNING [FinCausal20 {Task.CausalityDetection}/{split}]: {error}")
    df.to_parquet(f"./causality-detection/{split}.parquet", engine="pyarrow")


def convert_for_causal_candidate_extraction(split: str) -> None:
    task1_texts = _load_task1(split)
    relations_by_index = _load_relations_by_index(split)
    out = []
    for base, relations in relations_by_index.items():
        spans = sorted({relations[i]["cause"] for i in range(len(relations))}
                       | {relations[i]["effect"] for i in range(len(relations))})
        entity = [list(span) for span in spans]
        out.append({"index": f"fincausal20_{split}_{base}", "text": task1_texts[base], "entity": entity})
    df = pd.DataFrame(out).set_index("index")
    for error in verify_dataset(df, Task.CausalCandidateExtraction):
        print(f"WARNING [FinCausal20 {Task.CausalCandidateExtraction}/{split}]: {error}")
    df.to_parquet(f"./causal-candidate-extraction/{split}.parquet", engine="pyarrow")


def convert_for_causality_identification(split: str) -> None:
    task1_texts = _load_task1(split)
    relations_by_index = _load_relations_by_index(split)
    out = []
    for base, relations in relations_by_index.items():
        text = task1_texts[base]
        span_to_id: dict[tuple[int, int], str] = {}
        segments: dict[str, list[tuple[int, int]]] = {}
        causalatee_relations = []
        for rel in relations:
            ids = {}
            for role in ("cause", "effect"):
                span = rel[role]
                if span not in span_to_id:
                    eid = f"e{len(span_to_id) + 1}"
                    span_to_id[span] = eid
                    segments[eid] = [span]
                ids[role] = span_to_id[span]
            causalatee_relations.append(
                {"relationship": Relation.Procausal, "first": ids["cause"], "second": ids["effect"]}
            )
        marked_text = insert_entity_markers(text, segments)
        out.append({"index": f"fincausal20_{split}_{base}", "text": marked_text, "relations": causalatee_relations})
    df = pd.DataFrame(out).set_index("index")
    for error in verify_dataset(df, Task.CausalityIdentification):
        print(f"WARNING [FinCausal20 {Task.CausalityIdentification}/{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)